Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove inserted template in meteor 0.8.0

I am inserting templates using UI.render() and UI.insert().

When I tried to remove the template I inserted, it seems to stay in memory and the destroyed method is not called.

According to the documentation, it should clean up property if I use jquery to remove the element.

I'm testing it using the following code:

test.html:

<head>
  <title>removeTest</title>
    <style>
        #content {
            height: 500px;
            width: 500px;
            background-color: gray;
        }
    </style>
</head>    

<body><div id="content"></div></body>    

<template name="foo"><div id="{{id}}">Foo</div></template>

test.js:

if (Meteor.isClient) {
    UI.body.events({
        "click": function(event) {
            var instance = UI.renderWithData(Template.foo, { });
            UI.insert(instance, $("#content")[0]);
        }
    });    

    Template.foo.created = function() {
        this.data.id = "handle";
        var self = this;
        this.x = setInterval(function() { console.log("running...") }, 1000);
        setTimeout(function() { $("#handle").remove() }, 1000);
    };    

    Template.foo.destroyed = function() {
        // never called.
        clearTimeout(this.x);
    };
}

What did I do wrong?

Thanks.

like image 306
unional Avatar asked Apr 07 '14 08:04

unional


3 Answers

Some options to remove inserted templates:

a) Using a close event in your template.

Template.foo.events({
  'click a.close' : function(e, t) {
    e.preventDefault();

    t.__component__.dom.remove();
    return false;
  }
});

b) Using a helper, and instance reference

Template.foo.helpers({
  destroy: function() {
    this.dom.remove();
  }
});

var instance = UI.renderWithData(Template.foo, { });
UI.insert(instance, $("#content")[0]);
instance.destroy();
like image 162
s.meijer Avatar answered Oct 10 '22 03:10

s.meijer


This is currently a bug in Meteor and is being tracked in the following related GitHub issues:

  • https://github.com/meteor/meteor/issues/2079
  • https://github.com/meteor/meteor/issues/2128
  • https://github.com/meteor/meteor/issues/2145

It should be fixed when updates to Blaze are released.

like image 40
Andrew Mao Avatar answered Oct 10 '22 01:10

Andrew Mao


According to Avital back on April 19, the code is being rewritten (source).

In the meantime, if you take a look at the properties of your node element $("#handle")[0], you'll see you have one called $ui which corresponds to the DomRange object (code). If you call remove on the DomRange object, your destroyed callback will fire. In fact, it will fire the callbacks for any nested templates as well.

$("#handle")[0].$ui.remove()
like image 35
fletch Avatar answered Oct 10 '22 03:10

fletch