Backbone.js的简单视图事件不触发 [英] backbone.js simple view event not firing

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

问题描述

谁能告诉我,为什么下面不工作,请。我期待警报火,当我点击链接

Can someone tell me why the following doesnt work please. I am expecting the alert to fire when I click the link

<body>
    <a class="newnote" href="#">Add new note</a>
</body>

<script>
var note = Backbone.Model.extend({});

var notes = Backbone.Collection.extend({
    model: note,
    url: '<?= $this->createUrl('/filenotes/api'); ?>'
});

var note_view = Backbone.View.extend({
    el: 'table',

});

var Appview = Backbone.View.extend({
    el: $('body'),

    events: {
        "a click" : "showForm"
    },
    initialize: function(){
        //alert('hi');  
    },
    showForm: function(){
        alert('hi');
    }
});

var v = new Appview();
</script>

这里有一个的jsfiddle http://jsfiddle.net/neilcharlton/yj5Pz/1/

推荐答案

$(身体)选择是你的DOM之前加载射击,所以它的返回空从不绑定到链路

Your $("body") selector is firing before your DOM is loaded, so it's returning empty and never binding to the link.

骨干对象定义与对象定义的文字,这意味着它们会立即计算的定义,而不是当你实例化模式。

Backbone object definitions are defined with object literals, which means they get evaluated immediately on definition, not when you instantiate the model.

Backbone.View.extend({foo: "bar"})

在功能上与此相同:

Is functionally the same as this:

var config = {foo: "bar"};
Backbone.View.extend(config);

既然你有一个 $(身体)选择为的价值,它被评为一旦查看配置解析,这意味着DOM尚未加载,并且没有将被退回。

Since you have a $("body") selector as the value for el, it gets evaluated as soon as the View configuration is parsed, meaning the DOM has not yet loaded and nothing will be returned.

有许多用于解决这个选项...所有这些都涉及延迟选择器的评价在DOM加载后直到

There are a number of options for solving this... all of which involve delaying the evaluation of the selector until after the DOM is loaded.

我个人最喜欢的是选择在以实例化视图通过,DOM加载之后:

My personal favorite is to pass the selector in to the view at instantiation, after the DOM has loaded:

var AppView = Backbone.View.extend({
  // don't specify el here
});

$(function(){
  // after the DOM has loaded, select it and send it to the view
  new AppView({ el: $("body") });
}

也 - 样斯凯勒说,被宣布为您的活动不对

Also - like Skylar said, your event was declared wrong.

下面是一个工作的jsfiddle: http://jsfiddle.net/yj5Pz/5/

Here's a working JSFiddle: http://jsfiddle.net/yj5Pz/5/

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆