Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use X-editable on dynamic fields in a Meteor template now with Blaze?

I had x-editable working in Meteor 0.7.2 but since upgrading to 0.8.0 it no longer renders correctly. I tend to end up with a bunch of Empty tags. This is frustrating because the data is there, just not by the time the rendered function is fired.

<template name="clientPage">
    <header>{{> clientPageTitleUpdate}}</header>
</template>

<template name="clientPageTitleUpdate">
    <h1><span class="title-update editable" data-type="text" data-pk="{{_id}}" data-name="title" data-value="{{title}}">{{title}}</span></h1>
</template>


    Template.clientPageTitleUpdate.rendered = function() {

        console.log(this.$(".title-update").text());

        // set up inline as defaule for x-editable
        $.fn.editable.defaults.mode = 'inline';

        $(".title-update.editable:not(.editable-click)").editable('destroy').editable({

            url:    "empty",
            toggle: "dblclick",

            success: function (response, newValue) {
                // update value in db
                var currentClientId = $(this).data("pk");
                var clientProperties = { title: newValue };

                Clients.update(currentClientId, {$set: clientProperties}, function(error) {
                    if (error) {
                        Errors.throw(error.message)
                    }
                });
            }// success

        });

    }

I have tried the "new" rendered method of embeding the this into another template as explained here and it doesn't seem to work either.

What is the best way to use x-editable now that rendered only fires once and doesn't make sure the data is there.

I am using Iron Router and my templates are not embeded in an {{#each}} block which seems to be the basic solution to the new rendered model.

This question is related to this older topic about x-editable in a meteor template.

Any help whatsoever would be super appreciated here. I am at a loss. Thanks

like image 847
yankeyhotel Avatar asked Dec 04 '22 07:12

yankeyhotel


2 Answers

EDIT: Much easier to implement now in Meteor 0.8.3:

Template:

<template name="docTitle">
    <span class="editable" title="Rename this document" data-autotext="never">{{this}}</span>
</template>

Code:

Template.docTitle.rendered = ->
  tmplInst = this

  this.autorun ->
    # Trigger this whenever data source changes
    Blaze.getCurrentData()

    # Destroy old editable if it exists
    tmplInst.$(".editable").editable("destroy").editable
      display: ->
      success: (response, newValue) -> # do stuff

For this to be most efficient, make sure the data context of the editable template is only the field being edited, as in the example above with {{> docTitle someHelper}}.


Outdated information follows for Meteor 0.8.0 to 0.8.2

I also had to do this but wasn't sure about using the global helper in my app. So I tried to accomplish it by just changing the behavior of the editable.

The main things that needed to be done, after perusing the docs and source, were:

  • Set the value of the form from the field text
  • Override the display function so that reactivity of text updated by Meteor doesn't break
  • Make sure the above two functions don't break

Here's the code (apologies for Coffeescript):

Template.foo.rendered = ->
  container = @$('div.editable')
  settings =
    # When opening the popover, get the value from text
    value: -> $.trim container.text()
    # Don't set innerText ourselves, let Meteor update to preserve reactivity
    display: ->
    success: (response, newValue) =>
      FooCollection.update @data._id,
        $set: { field: newValue }
      # Reconstruct the editable so it shows the correct form value next time
      container.editable('destroy').editable(settings)
  container.editable(settings)

This is ugly because it destroys and re-creates the popover after setting a new value, so that the form field updates from the correct value.

After some more reverse engineering, I found a cleaner way to do this that doesn't involve destroying the editable. Gadi was right on that container.data().editableContainer.formOptions.value has something to do with it. It's because this value is set after the update because x-editable thinks it can cache this now. Well, it can't, so we replace this with the original function so the value continues being updated from the text field.

Template.tsAdminBatchEditDesc.rendered = ->
  container = @$('div.editable')
  grabValue = -> $.trim container.text() # Always get reactively updated value
  container.editable
    value: grabValue
    display: -> # Never set text; have Meteor update to preserve reactivity
    success: (response, newValue) =>
      Batches.update @data._id,
        $set: { desc: newValue }
      # Thinks it knows the value, but it actually doesn't - grab a fresh value each time
      Meteor.defer -> container.data('editableContainer').formOptions.value = grabValue

Notes:

  • $.trim above was taken from the default behavior to render value
  • For more discussion about this see https://github.com/nate-strauser/meteor-x-editable-bootstrap/issues/15
  • This is all an ugly hack, hopefully in the future we'll see better support for two-way variable bindings in Meteor.

I will try to make this more concise in the future pending better support from Meteor for depending on data reactively.

like image 178
Andrew Mao Avatar answered Apr 30 '23 03:04

Andrew Mao


Updated for Meteor 0.8.3+

This covered all cases for me (see below the code). This uses pretty fine-grained reactivity and will update the x-editable instance only when the specified value changes.

Template:

<!-- once off for your entire project -->
<template name="xedit">
    {{> UI.contentBlock}}
</template>

<!-- per instance -->
<template name="userInfo">
  {{#xedit value=profile.name}}<a>{{profile.name}}</a>{{/xedit}}
</template>

Client Javascript (for Meteor 0.8.3+):

// once off for your entire project
Template.xedit.rendered = function() {
  var container = this.$('*').eq(0);
  this.autorun(function() {
    var value = Blaze.getCurrentData().value;
    var elData = container.data();
    if (elData && elData.editable) {
      elData.editable.setValue(value, true);
      // no idea why this is necessary; xeditable bug?
      if (elData.editableContainer)
        elData.editableContainer.formOptions.value = elData.editable.value;
    }
  });
}

// per instance; change selector as necessary
Template.userInfo.rendered = function() {
  // Note you don't need all the :not(.editable) stuff in Blaze
  this.$('a').editable({
    success: function(response, newValue) {
      // according to your needs
      var docId = $(this).closest('[data-user-id]').attr('data-user-id');
      var query = { $set: {} }; query['$set']['profile.username'] = newValue;
      Meteor.users.update(docId, query);
    }
  });
});

You can see it in action at http://doingthiswithmeteor.com/ (with two windows open). You need to be logged in, but try change any of your info on the "me" page.

  1. Setup x-editable in rendered() as usual
  2. Ability for custom display functions, "empty" values, etc.
  3. Open in two windows. Change value in win1, click on value in win2.. the POPUP should display the correct value.
  4. Support for custom types like dates and arrays from custom helpers

Just implemented this... still doing some testing but feedback welcome. This replaces my previous helper workaround.

like image 33
gadicc Avatar answered Apr 30 '23 04:04

gadicc