如何将 jquery-ui 应用到 Backbone.js 视图?
我是 Backbone.js 的新手。我已经为页面上已存在的按钮创建了一个视图。当视图初始化时,我将 jquery-ui 应用于按钮:
var ButtonView = Backbone.View.extend({
el: $('#ButtonId'),
initialize: function () {
$(this.el.selector).button();
}
});
此方法有效,但我想知道是否有一个更简单的选择器可以使用,而不是 $(this.el.selector)
?起初我以为我可以只执行 el.button();
但这不起作用。
或者是否有更好/更简单的方法来处理整个过程?
I am new to Backbone.js. I have created a View for a button that already exists on the page. I apply jquery-ui to the button when the view is initialized:
var ButtonView = Backbone.View.extend({
el: $('#ButtonId'),
initialize: function () {
$(this.el.selector).button();
}
});
This method works, but I am wondering if there a simpler selector I could use rather than $(this.el.selector)
? At first I thought I would be able to just do el.button();
but that does not work.
Or is there a better/simpler way to approach the whole process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以向你保证 el.button(); 有效
但是......
你需要记住当你的视图jquery选择器被执行时。
当你像你一样输入它时,你的 jQuery 选择器将在解析视图代码时执行,
意思是,这主要发生在你的 dom 尚未准备好加载时。
您最好稍后像这样传递
el
:现在,您的视图在文档准备好时实例化,按钮元素被传递,因为 dom 已准备好并且您的选择器解析为按钮元素。您可以愉快地使用 el.button(); 来在其上应用某些内容。
示例: http://jsfiddle.net/saelfaer/KEQQB/
编辑
另一种方法就是将你的 elementselector 定义为 el 参数,并且只像你一样执行它。
这也可以,但是你只能在给定的按钮上使用这个视图,除非你覆盖它,第一个例子对于重用代码来说更干净,你可以实例化它3次,并且每次你都可以将另一个按钮传递给...
示例: http://jsfiddle.net/saelfaer/KEQQB/6/
旁注
在旁注中,我建议使用 render 方法,您可以在 init 中自由地执行此操作,但我相信 render 方法应该处理此问题。
i can assure you
el.button();
worksbut...
you need to keep in mind when your view jquery selector is executed.
when you type it like you did, your jQuery selector is executed when the view code is parsed,
meaning, this mostly happens when your dom was not ready loading.
you can best pass the
el
in later like this:now, your view is instantiated on document ready, the button element is passed because the dom was ready and your selector resolves to the button element. and you can happily use
el.button();
to apply something on it.example: http://jsfiddle.net/saelfaer/KEQQB/
edit
another way to do it is to define your elementselector as the el argument, and only execute it like you did.
this will work as well, but you would only be able to use this view on your given button unless you override it, the first example is cleaner for reusing code, you could instantiate it 3 times and each of them you could pass another button to...
example: http://jsfiddle.net/saelfaer/KEQQB/6/
sidenote
on a sidenote i'd suggest using the render method, you are free to do this in the init, but i believe the render method is the one that should be handling this.