在 Backbone 中执行视图混合的正确方法 [英] Proper way of doing view mixins in Backbone

查看:14
本文介绍了在 Backbone 中执行视图混合的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在扩展基本主干视图,并且每个部分都有一个基本视图,以便我可以在多个级别上进行扩展.我的问题是,进行视图混合的最有效方法是什么:可以混合到任何视图中的可重用视图部分.例如:

I extend base backbone views all the time and have a base view per section so that I can extend on multiple levels. My question is, what's the most effective way of doing view mixins: reusable view partials that can be mixed in to any view. For example:

var BaseProfile = Backbone.View.extend({ ...});
var UserProfile = BaseProfile.extend({ ...});
var VideoSupport = Backbone.View.extend({ ...});

VideoSupport 视图(一个事件对象和一些方法)与 UserProfile 视图混合的最佳方法是什么?

What's the best way to mixin VideoSupport view (an event object and a few methods) with UserProfile view?

推荐答案

underscore.js 库提供了一个 extend 方法,可以执行您想要的操作.您可以在任何对象上定义功能,然后从字面上复制 &将该对象的所有方法和属性粘贴到另一个对象.

The underscore.js library provides an extend method that does what you want. You can define functionality on any object, and then quite literally copy & paste all of the methods and attributes from that object to another.

Backbone 在视图、模型和路由器上的 extend 方法是对 underscore 的 extend 的封装.

Backbone's extend methods on Views, Models, and Routers are a wrapper around underscore's extend.

 var MyMixin = {
  foo: "bar",
  sayFoo: function(){alert(this.foo);}
}

var MyView = Backbone.View.extend({
 // ...
});

_.extend(MyView.prototype, MyMixin);

myView = new MyView();
myView.sayFoo(); //=> "bar"

这篇关于在 Backbone 中执行视图混合的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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