3vot-model 中文文档教程

发布于 10年前 浏览 40 更新于 3年前

clay-model

基于 SpineJS 模型

类方法

Model.setup(modelName, attributes…)

的具有承诺的 Javascript 模型实现var User = Model.setup("User", [ "firstname", "lastname" ]);

设置模型及其属性。 这对每个模型都是必需的,并且应该在其他任何事情之前被调用。

Model.bind(eventName, function)

将事件侦听器绑定到模型。 这些是在模型的上下文中执行的。

User.bind("刷新变化", function(user){ alert("#{user.name} 改变了!")) } 有关详细信息,请参阅事件。

Model.trigger(eventName, data…)

触发自定义事件,请参阅事件了解更多信息。

Model.unbind([eventName, function])

取消绑定事件,请参阅事件指南了解更多信息。

Model.find(id, [notFound])

按 ID 查找记录 - 返回记录实例。 如果记录不存在,@notFound 将运行,除非自定义回调也被传入。

var user = User.find("1")

Model.exists(id)

返回一个布尔值,指示具有指定 ID 的记录是否存在。

var user = User.exists("1")

Model.refresh(recordsArray, [options])

附加到所有存储的记录,而不调用任何创建、更新、保存或销毁事件。 唯一会被触发的事件是刷新事件。 您可以通过选项 {clear: true} 擦除所有现有记录。 @refresh 在内部调用 fromJSON(),因此您也可以将 JSON 而不是数组传递给它。

User.refresh([{id: 1, name: "test"}, {id: 2, name: "test2"}])

Model.select(function)

选择回调函数返回true的所有记录。

bobs = User.select(函数(用户){ 返回(用户名==“鲍勃”); }

Model.findByAttribute(name, value)

查找具有给定属性 & 的第一条记录 价值。

bob = User.findByAttribute("name", "bob")

Model.findAllByAttribute(name, value)

查找具有给定属性 & 的所有记录 价值。

bobs = User.findAllByAttribute("name", "bob")

Model.each(callback)

迭代每条记录,将其传递给回调函数。

User.each(函数(用户){ 警报(用户名) });

Model.all()

返回每个实例的克隆副本。

users = User.all()

Model.slice(begin[, end])

返回从开始到但不包括结束的实例的克隆副本。

allUsersExceptFirst3 = User.slice(3) users7through13 = User.slice(6,13)

Model.first([x])

返回第一条记录的克隆副本。 或前 x 条记录的数组

Model.last([x])

返回最后一条记录的克隆副本,或最后 x 条记录的数组

Model.count()

返回总记录数。

Model.deleteAll()

删除每条记录而不触发任何事件。

Model.destroyAll(options)

销毁每条记录,在每条记录上触发销毁事件。

Model.update(id, attributes)

使用给定的属性更新具有匹配 ID 的记录。

Model.create(attributes)

创建具有给定属性的新记录。 如果记录验证失败则返回 false,如果成功则返回新创建的记录。

Model.destroy(id, options)

销毁具有给定 ID 的记录。

Model.toJSON()

效用函数使模型具有有效的 JSON 表示(显示所有记录)。

Model.fromJSON(json)

将表示数组或单例的 JSON 字符串传递给 @fromJSON()。 返回一个数组或未保存的模型实例。

Model.proxy(function)

在代理中包装一个函数,以便它始终在模型的上下文中执行。 这是一个 JavaScript 兼容性特性,不应在 CoffeeScript 中使用。

create = Model.proxy(Model.create)

Model.setup

Model.setup(name, [attributes…])

创建新模型类的替代方法。 这是一个 JavaScript 兼容性特性,不应在 CoffeeScript 中使用。

var User = Model.setup("User", ["firstname", "lastname"])

Instance methods

newRecord

指示记录是否已保存的布尔值。 请改用 isNew() 。

isNew()

返回一个布尔值,指示记录是否已保存。

isValid()

返回一个布尔值,指示记录是否已通过验证。

validate()

默认情况下是一个 noop。 覆盖它以提供自定义验证。 如果记录无效,则返回包含错误消息的字符串。 例如:

Model.prototype.validate = function(){ “需要姓名”除非@name }

load(attributes)

载入一组属性,设置属性。

用户 = 新用户 user.load(name: "鲍勃爵士") attributes()

将属性的散列返回到值。

eql(record)

返回一个布尔值,指示其他记录是否与当前实例相等(即相同的类和 ID)。

if(user.eql(anotherUser)) alert("Yah!")

save()

创建或更新记录,如果记录验证失败则返回 false,如果记录保存成功则返回 self。 在保存期间,会触发 beforeSave、change 和 save 事件。 此外,创建或更新事件将根据记录是否已创建/更新而被触发。

user = new User(name: "罗宾爵士") user.save()

alert("#{user.id} 已保存") user = User.find(user.id)

updateAttribute(name, value)

设置单个属性,保存实例。

用户 = 新用户 user.updateAttribute("name", "Green Knight")

updateAttributes(attributes)

更新具有给定属性的记录,保存记录。

user = User.create() user.updateAttributes(name: "Sir Galahad the Pure")

destroy()

销毁记录,将其从记录存储中移除并触发 destroy 事件。

user = User.create()

user.destroy()

Destroy 还将取消绑定它正在侦听的模型和对象的事件侦听器。

dup()

返回一条新的未保存记录,与当前记录具有相同的属性,保存ID,将为空。

user = User.create(name: "贝德维尔爵士") dup = user.dup() assertEqual( dup.name, "Sir Bedevere" )

返回记录的原型克隆。 这在内部用于动态记录,可能不是您需要担心的事情。

clone()

返回记录的原型克隆。 这在内部用于动态记录,可能不是您需要担心的事情。

reload()

从已保存的记录中重新加载记录的属性。

toJSON()

返回记录的属性。 这用于 JSON 序列化:

record = new User(name: "Sir Lancelot the Brave")

assertEqual( JSON.stringify(record), '{"id":"foo","name":"Sir Lancelot the Brave" }' )

$.post("/record.json", JSON.stringify(record))

toString()

返回记录的字符串表示形式。 用于在控制台中显示记录的实用函数。

exists()

返回一个布尔值,指示记录是否已保存。 类似于 isNew(),但它实际上检查模型记录存储。

bind(name, function)

专门绑定到此记录上的事件。 on 是一个可用的别名。

trigger(name, [data…])

专门针对这条记录触发一个事件。 这也将传播到模型。

unbind([events, callback])

取消绑定所有事件,或仅取消绑定某些事件(作为逗号分隔列表),或给定事件的特定回调。 off 是一个可用的别名

proxy(function)

A JavaScript 兼容性函数,它将包装给定的函数,以便它始终在记录的上下文中执行。

Ajax

模型带有用于 Ajax 或其他连接器的接口。 创建模型后定义连接器

使用Model.ajax = AjaxConnector;

; 您可以在 clay-model-vfr

Model.create( values, options )、modelInstance.save( options ) 和 modelInstance.destroy(options)

中找到连接器的引用,它们都采用选项参数,这里有一些值

ignoreAjax: [true /false]:只会在本地进行修改,而不会将更改发送到服务器。

API

用于执行自定义 API 调用,由 Ajax Connector 定义

``` User.api(参数...);

clay-model

A Javascript Model Implementation with Promises based on SpineJS Model

Class methods

Model.setup(modelName, attributes…)

var User = Model.setup("User", [ "firstname", "lastname" ]);

Set up the model and its attributes. This is required for every model, and should be called before anything else is.

Model.bind(eventName, function)

Bind event listeners to the model. These are executed in the context of the model.

User.bind("refresh change", function(user){ alert("#{user.name} changed!")) } See events for more information.

Model.trigger(eventName, data…)

Trigger a custom event, see events for more information.

Model.unbind([eventName, function])

Unbind events, see the events guide for more information.

Model.find(id, [notFound])

Find records by ID - returning the record instance. If the record doesn't exist, @notFound will be run unless a custom callback was also passed in.

var user = User.find("1")

Model.exists(id)

Returns a boolean indicating if the record with the specified ID exists or not.

var user = User.exists("1")

Model.refresh(recordsArray, [options])

Appends to all the stored records, without calling any create, update, save or destroy events. The only event that will be triggered is the refresh event. You can pass the option {clear: true} to wipe all the existing records. Internally @refresh calls fromJSON(), so you can also pass it JSON instead of an array.

User.refresh([{id: 1, name: "test"}, {id: 2, name: "test2"}])

Model.select(function)

Select all records that the callback function returns true to.

bobs = User.select(function(user){ return( user.name == "bob" ); }

Model.findByAttribute(name, value)

Find the first record that has the given attribute & value.

bob = User.findByAttribute("name", "bob")

Model.findAllByAttribute(name, value)

Find all records that have the given attribute & value.

bobs = User.findAllByAttribute("name", "bob")

Model.each(callback)

Iterate over every record, passing it to the callback function.

User.each(function(user){ alert(user.name) });

Model.all()

Returns a cloned copy of every instance.

users = User.all()

Model.slice(begin[, end])

Returns a cloned copies of instances from begin up to but not including end.

allUsersExceptFirst3 = User.slice(3) users7through13 = User.slice(6,13)

Model.first([x])

Returns a cloned copy of the first record. or an array of the first x records

Model.last([x])

Returns a cloned copy of the last record, or an array of the last x records

Model.count()

Returns the count of total records.

Model.deleteAll()

Deletes every record without triggering any events.

Model.destroyAll(options)

Destroys every record, triggering a destroy event on every record.

Model.update(id, attributes)

Updates the record with the matching ID, with the given attributes.

Model.create(attributes)

Creates a new record with the given attributes. Returns false if the record's validation fails, or the newly created record if successful.

Model.destroy(id, options)

Destroys the record with the given ID.

Model.toJSON()

Utility function so the model has a valid JSON representation (shows all records).

Model.fromJSON(json)

Pass a JSON string, representing either an array or a singleton, to @fromJSON(). Returns an array or unsaved model instances.

Model.proxy(function)

Wrap a function in a proxy so it will always execute in the context of the model. This is a JavaScript compatibility feature, and shouldn't be used in CoffeeScript.

create = Model.proxy(Model.create)

Model.setup

Model.setup(name, [attributes…])

Alternative method for creating a new model class. This is a JavaScript compatibility feature, and shouldn't be used in CoffeeScript.

var User = Model.setup("User", ["firstname", "lastname"])

Instance methods

newRecord

Boolean indicating if the record has been saved or not. Use isNew() instead.

isNew()

Returns a boolean indicating if the record has been saved or not.

isValid()

Returns a boolean indicating if the record has passed validation.

validate()

By default a noop. Override this to provide custom validation. Return a string, containing the error message, if the record isn't valid. For example:

Model.prototype.validate = function(){ "Name required" unless @name }

load(attributes)

Load a set of properties in, setting attributes.

user = new User user.load(name: "Sir Bob") attributes()

Returns a hash of attributes to values.

eql(record)

Returns a boolean indicating if the other record is equal (i.e. same class and ID) as the current instance.

if(user.eql(anotherUser)) alert("Yah!")

save()

Creates or updates the record, returning false if the record's validation fails, or self if the record saves successfully. During a save, the beforeSave, change and save events are triggered. Also the create or update events will be fired depending on whether the record was created/updated.

user = new User(name: "Sir Robin") user.save()

alert("#{user.id} was saved") user = User.find(user.id)

updateAttribute(name, value)

Sets a single attribute, saving the instance.

user = new User user.updateAttribute("name", "Green Knight")

updateAttributes(attributes)

Updates a record with the given attributes, saving the record.

user = User.create() user.updateAttributes(name: "Sir Galahad the Pure")

destroy()

Destroys the record, removing it from the record store and triggering the destroy event.

user = User.create()

user.destroy()

Destroy will also unbind event listeners for the model and objects it was listening to.

dup()

Returns a new unsaved record, with the same attributes as the current record, save the ID, which will be null.

user = User.create(name: "Sir Bedevere") dup = user.dup() assertEqual( dup.name, "Sir Bedevere" )

Returns a prototype clone of the record. This is used internally for Dynamic Records, and is probably not something you need to worry about.

clone()

Returns a prototype clone of the record. This is used internally for Dynamic Records, and is probably not something you need to worry about.

reload()

Reloads a record's attributes from its saved counterpart.

toJSON()

Returns the record's attributes. This is used for JSON serialization:

record = new User(name: "Sir Lancelot the Brave")

assertEqual( JSON.stringify(record), '{"id":"foo","name":"Sir Lancelot the Brave"}' )

$.post("/record.json", JSON.stringify(record))

toString()

Returns a string representation of the record. A utility function used to display the record in the console.

exists()

Returns a boolean indicating whether the record has saved. Similar to isNew(), but it actually checks the models record store.

bind(name, function)

Bind to an event specifically on this record. on is an available alias.

trigger(name, [data…])

Trigger an event specifically on this record. This will propagate up to the model too.

unbind([events, callback])

Unbind all events, or just certain events (as a comma seperated list), or a specific callback for given events. off is an available alias

proxy(function)

A JavaScript compatibility function, that will wrap the given function so that it's always executed in the context of the record.

Ajax

Model comes with an interface for Ajax or other connectors. Define the connector after creating the model with

Model.ajax = AjaxConnector;

You can find a reference of a Connector in clay-model-vfr

Model.create( values, options ), modelInstance.save( options ) and modelInstance.destroy(options)

All take an options argument, here are some values

ignoreAjax: [true/false]: Will only make modifications locally without sending changes to the server.

API

Used to execute custom API Calls, is defined by Ajax Connector

``` User.api( arguments… );

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文