Backbone.js的自定义构造函数? [英] Backbone.js custom constructor?

查看:67
本文介绍了Backbone.js的自定义构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找上我的模型创建一个自定义构造函数的一些例子。我想要的结构模型/数据不同那么就设置它为属性。

I'm looking for some examples for creating a custom constructor on my models. I want the structure the model/data differently then just setting it as attributes.

有人能告诉我如何做一些基本的例子吗?

Can somebody show me some basic example of how to do this?

谢谢!

推荐答案

如果你真的想重写构造函数,传递构造属性 Backbone.Model.extend(),例如:

If you really want to override the constructor, pass a constructor property to Backbone.Model.extend(), e.g.:

var Klass = Backbone.Model.extend( {

  constructor : function ( attributes, options ) {

    // ...

  }

} );

如果您想从您的自定义构造函数中调用内置的构造函数,你可以这样做:

If you want to call the built-in constructor from your custom constructor, you can do something like:

var Klass = Backbone.Model.extend( {

  constructor : function ( attributes, options ) {

    Backbone.Model.apply( this, arguments );

  }

} );

或者,如果你不想有重复包含父类中的所有在子类中的变量的名称,或者你不想担心变量变化的,你可以这样做的价值以下内容:

Or if you don't want to have to repeat the name of the variable containing the parent class all over the sub class, or you don't want to worry about the value of that variable changing, you can do something like the following:

var Klass;

var parent_klass = Backbone.Model.prototype;

( function ( parent_klass ) {

  Klass = parent_klass.constructor.extend( {

    constructor : function ( attributes, options ) {

      parent_klass.constructor.apply( this, arguments );

    }

  } );

} )( parent_klass );

或者,如果你preFER的方式<一个href=\"http://stackoverflow.com/questions/10399334/backbone-js-custom-constructor/10413335#12347014\">@Claude建议,但子类而不是父类变数名称中重复子类变量名:

Or if you prefer the way @Claude suggests, but repeating the sub class variable name within the sub class instead of the parent class var name:

var Klass = Backbone.Model.extend(

  {

    constructor : function ( attributes, options ) {

      Klass.parent_klass.constructor.apply( this, arguments );

    }

  },

  {

    parent_klass : Backbone.Model.prototype

  }

);

如果你想比这更多的建议,你就会有更具体的了解你想要完成的任务。

If you want more advice than that, you'll have to be more specific about what you want to accomplish.

什么,你只是想后做了内置构造的功能,你应该做初始化()

Anything that you just want to do after the built-in constructor functionality, you should probably do in initialize().

这篇关于Backbone.js的自定义构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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