简体   繁体   English

$(this.el).find()在事件处理程序中起作用,而不在初始化函数中起作用(backbone.js)

[英]$(this.el).find() works in event handler, not in initialize function (backbone.js)

I am using backbone.js to create a View which contains a Like button. 我正在使用bone.js创建一个包含“ Like按钮的视图。 The model of this View contains the attribute is_liked , and if its value is 1 , then the function setStateLike called will change the style of the Like button. 此View的模型包含is_liked属性,如果其值为1 ,则调用的setStateLike函数将更改Like按钮的样式。

Problem: I am not able to select the button using this.setStateLike() in the initialize function. 问题:我无法在initialize函数中使用this.setStateLike()选择按钮。 Doing so just returns a [] . 这样做只返回一个[] However, when I define this.setStateLike as a click event handler, selecting the button works! 但是,当我将this.setStateLike定义为单击事件处理程序时,选择按钮有效! The stranger thing is that this.setStateLike() called within initialize is able to select $(this.el) , but not $(this.el).find() ! 奇怪的是,在initialize调用的this.setStateLike()能够选择$(this.el) ,但不能选择$(this.el).find()

Any idea what has happened here and how can it be fixed? 知道这里发生了什么,如何解决? Thanks! 谢谢!

PhotoListItemView = Backbone.View.extend({
    tagName: 'div',
    className: 'photo_box',

    events: {
        'click': 'setStateLike'
    },

    initialize: function() {
        this.setStateLike();
    },

    render: function() {
        $(this.el).html( this.template( this.model.toJSON() ) );
        return this;
    },

    setStateLike: function() {
        console.log( $(this.el).find('#like') );  // returns []
        if(this.model.get('is_liked')) {
            console.log( $(this.el) );        // returns correctly
            console.log( $(this.el).find('#like') );  // returns []
            // Change icon to Active state
            $(this.el).find('#like.photo_btn').addClass('photo_btn_active').attr('id', 'unlike');
        }
    }
});

If your script comes before the bulk of the body HTML and if the initialize function is being called immediately, that's your issue: the DOM isn't actually built yet, so no elements can be selected. 如果您的脚本位于正文HTML的大部分内容之前,并且如果立即调用了initialize函数,那么这就是您的问题:DOM尚未真正构建,因此无法选择任何元素。 Either run the script at the end of the </body> , or use jQuery's DOM-ready handler . </body>的末尾运行脚本,或使用jQuery的DOM-ready处理程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM