本文介绍了Backbone.js的单击事件不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过Backbone.js的观点一个非常基本的教程去。

Going through a very basic tutorial on backbone.js views.

预期的行为是调用被点击#sayhello按钮时渲染功能。渲染仅仅使用jQuery的HTML的方法来把你好巴德·阿伯特在El。

The expected behavior is to call the render function when #sayhello button is clicked. Render simply uses jQuery's html method to put "hello Bud Abbot" in el.

但是,当我点击#sayhello按钮,没有任何反应。没有错误或任何东西。我设置萤火断点,看它只是跳过渲染功能。

But when I click the #sayhello button, nothing happens. No errors or anything. I set a breakpoint in firebug and watch it just skip the render function.

这里的JS:

App = (function($){
jQueryView = Backbone.View.extend({
    initialize: function(){
        this.el = $(this.el);
    }
});

HelloWorldView = jQueryView.extend({
    el: $('#helloworld'),
    events:{ 'click #sayhello': 'render'
    },
    initialize: function(params){
        jQueryView.prototype.initialize.call(this);
        this.name = params.name;
    },

    render: function(){
        console.log("rendering");
        this.el.html("hello " + this.name);
    }
});

var self = {};
self.start = function(){
    new HelloWorldView({name: 'Bud Abbot'});
};
return self;

});

和这里的HTML:

    <div id="helloworld"></div>
<button id="sayhello">Say Hello</button>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

什么似乎很奇怪的是当我改变这样的:

What seems strange is when I change this:

new HelloWorldView({name: 'Bud Abbot'});

这样:

new HelloWorldView({name: 'Bud Abbot'}).render();

渲染方法被调用,但是当我尝试用一​​个事件来做到这一点 - 没有骰子。任何帮助理解我做错了什么是大大AP preciated。

the render method is called, but when I try to do it with an event - no dice. Any help to understand what I'm doing wrong is greatly appreciated.

推荐答案

这是因为#sayhello不是你的视图的一部分。尝试把里面#sayhello #helloworld:

It's because #sayhello is not part of your view. Try putting #sayhello inside #helloworld:

<div id="helloworld">
    <button id="sayhello">Say Hello</button>
</div>

这篇关于Backbone.js的单击事件不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 03:17