Meteor Template.onRendered or Template.rendered for using a jquery library?

霸气de小男生 提交于 2019-12-20 07:13:04

问题


I want to use chosen(a jquery library) with meteor and I just need to use this code:

    $('#ship').chosen();

I tried using .onRendered but I need to wait, if I want it to work

Template.createTradeForm.onRendered(function(){
    //Strange bug, need to wait here or it doesn't work..
    setTimeout(function(){
        $('#ship').chosen();
    }, 2000);
});

Same problem with this solution:

Template.createTradeForm.rendered = function(){
    //here again, I need to wait or it doesn't work
    setTimeout(function(){
        $('#ship').chosen();
    }, 2000);
};

Is there any other solutions to this problem? This setTimeout isn't really good here.

Edit My helper as requested

Template.createTradeForm.helpers({
    'getShips': function(){
        return Ship.find()
    }
});

回答1:


wrap your code inside Meteor.defer, like this:

Template.createTradeForm.onRendered(function(){
    Meteor.defer(function(){
        $('#ship').chosen();
    });
});

Meteor.defer corresponds a setTimeout of 0 and it's not in docs. It typically solve cases where something in the DOM that you're depending on has not yet rendered.

Some refs: 1, 2, 3




回答2:


I can only speculate on the causes as more debug information would be required. (What exactly happens without timeout? Is the DOM element being found, is the jQuery plugin chosen being found etc.)

First of all rendered and onRendered are the same thing and the latter is the current version while rendered is kept for compatibility with older code. One important thing to know that both runs exactly once only. For your problem my guess is, that you are seeing some timing issue caused by not yet loaded subscription data. Try using a subscribe where you set a reactive variable.

    Meteor.subscribe('items', function() {
        readyItems.set(true);
    });

Then depend on the reactive variable to use the chosen:

    Tracker.autorun(function() {
        if(readyItems.get()) $('#ship').chosen();
    });


来源:https://stackoverflow.com/questions/31410615/meteor-template-onrendered-or-template-rendered-for-using-a-jquery-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!