骨干模型中的"this"是什么? [英] What is `this` inside a Backbone model?

查看:84
本文介绍了骨干模型中的"this"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一些骨干,并且对模型内部的this感到困惑.

I'm learning some Backbone and I'm confused as to what this is inside of the model.

Person = Backbone.Model.extend({
    initialize: function() {
        console.log('hello world');
        this.bind("change:name", function() {
            console.log(this.get('name') + " is now the value for name");
        });
        this.bind('invalid', function( model, error ) {
            console.error(error);
        });
    },
    defaults: {
        name: "Bob Hope",
        height: "unknown"
    },
    validate: function ( attributes ) {
        if( attributes.name == 'Joe' ) {
            return "Uh oh, you're name is Joe!";
        }
    }
});
var person = new Person();
person.set({name: "Joe", height:"6 feet"}, {validate:true});
console.log(person.toJSON());

this.bind中发生了什么?什么是change:name? initializedefaults仅仅是JavaScript对象内部的方法吗?

What is going on in this.bind? What is change:name? Are initialize and defaults simply just methods inside of a javascript object?

推荐答案

this是模型的实例.

.bind .on 方法的别名://backbonejs.org/#Events"rel =" nofollow noreferrer> backbone.Events 模块,可让您在对象上绑定事件处理程序

.bind is an alias for .on method inside backbone.Events module which allows you to bind event handlers on an object

change:name 只是事件名称,它允许您跟踪模型的更改名为'name'的属性.

initialize 是构造函数方法,在实例化模型时将首先调用该方法.

initialize is a constructor method which will be called initially when you instantiate the model.

defaults 是设置默认模型的对象(或者可以是函数)属性.

defaults is an object (or it can be a function) that sets default model attributes.

所以initializedefaults确实是对象内部的方法(除了defaults也可以是属性),但是它们对主干具有特殊含义.然后,该对象将使用Backbone.Model的所有其他方法和属性进行扩展,从而使其成为一个功能模型.

So initialize and defaults are indeed methods inside an object (except that defaults can be also a property), but they have special meaning for backbone. And that object is extended with all other methods and properties of Backbone.Model which makes it a functional model.

骨干文档

这篇关于骨干模型中的"this"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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