Sajid Ahmad
Sajid Ahmad

Reputation: 1144

Render the meteor template manually when database changes occur

I have a meteorjs template which I am using to render some records. what I want to do is, when any change occurs in database , i want to call the template render method manually. Can I reload only a single template from the DOM to reflect the changes? my code is

<template name="textlines">
<table class="table table-striped table-bordered table-condensed table-hover listing"
               id="content_listing-table">
            <thead>
            <tr>
                <th>Text Lines</th>
            </tr>
            </thead>
            <tbody>
            {{#each textline}}
            <tr>
                <td>
                    <a href="#" data-id={{_id}} class="edit"> {{texts}}</a>
                </td>
            </tr>
            {{/each}}     
           </tbody>
        </table>
</template>

my meteor rendered method is like

Template.textlines.rendered = function () {
$("#content_listing-table").dataTable();
}

now i want to call this Template.textlines.rendered method manually after CRUD oprations on database. i don't know what i am asking is right or wrong, is it possible or not. I am having some problems with dataTables. so i want to refresh the template manually each time to add the contents return by the database to the dataTable. thanks

Upvotes: 1

Views: 338

Answers (2)

jrullmann
jrullmann

Reputation: 2978

It looks like you're using the jQuery DataTables plugin, and you're having trouble keeping the DOM maintained by the plugin updated with your database.

If so, you can observe your collection and use their API to make changes.

For example:

Template.textlines.created = function() {
    var _watch = Collection.find({});
    var handle = _watch.observe({
        addedAt: function (doc, atIndex, beforeId) {
            $('#content_listing-table').dataTable().fnAddData(doc);
        },
        changedAt: function(newDoc, oldDoc, atIndex) {
            $('#content_listing-table').dataTable().fnUpdate(newDoc, atIndex);
        },
        removedAt: function(oldDoc, atIndex) {
            $('#content_listing-table').dataTable().fnDeleteRow(atIndex);
        }
    });
};

There's a lot more information in this StackOverflow answer.

Upvotes: 3

Donny Winston
Donny Winston

Reputation: 2442

Hmm. I suspect that the upcoming Meteor UI release will make jQuery UI plugins work properly in Meteor and thus not tempt one to apply Meteor anti-patterns, but here is a stab at something that may accomplish what you want:

Deps.autorun(function () {
  var htmlString = Template.textlines({textlines: Textlines.find()});
  $("#content_listing-table").replaceWith(htmlString);
  $("#content_listing-table").dataTable();
});

With this, you'll want to replace {{> textlines}} with <table id="content_listing-table">.

Upvotes: 1

Related Questions