正确折叠和重建嵌套模型?

时间:2011-10-08 10:39:34

标签: javascript backbone.js

我有一个带有嵌套集合和模型的骨干模型。

我使用骨干关系来自动构建嵌套模型,但发现在现有父模型上设置数据时,它会创建嵌套模型来代替现有模型,但不会更新它们。

现在我想出了这个,我需要找出折叠和重建包含嵌套集合/模型的骨干模型的最佳方法。

任何指针都会很棒,谢谢!

2 个答案:

答案 0 :(得分:0)

您可以定义渲染的内容以及视图的数据更改时未呈现的内容。您可以确保绑定到“更改”的事件仅呈现您想要的内容。您还可以绑定事件以更改某些属性。您不必只使用全方位的“更改”。

object.bind('change:attribute', callback);

答案 1 :(得分:0)

我决定使用这个我在CoffeeScript中重建的解决方案来自Henrik Joreteg的一个例子。

# builds and return a simple object ready to be JSON stringified
xport: (opt) ->
    result = {}
    settings = _({recurse: true}).extend(opt || {})

    process = (targetObj, source) ->

        targetObj.id = source.id || null
        targetObj.cid = source.cid || null
        targetObj.attrs = source.toJSON()

        _.each source, (value, key) ->
            # since models store a reference to their collection
            # we need to make sure we don't create a circular refrence
            if settings.recurse
                if (key isnt 'collection' && source[key] instanceof Backbone.Collection)

                    targetObj.collections = targetObj.collections || {}
                    targetObj.collections[key] = {}
                    targetObj.collections[key].models = []
                    targetObj.collections[key].id = source[key].id || null

                    _.each source[key].models, (value, index) ->
                        process(targetObj.collections[key].models[index] = {}, value)

                else if (source[key] instanceof Backbone.Model)

                    targetObj.models = targetObj.models || {}
                    process(targetObj.models[key] = {}, value)

    process(result, @)

    return result


#rebuild the nested objects/collections from data created by the xport method
mport: (data, silent) ->

    process = (targetObj, data) ->
        targetObj.id = data.id || null
        targetObj.set(data.attrs, {silent: silent})

        # loop through each collection
        if data.collections

            _.each data.collections, (collection, name) ->
                targetObj[name].id = collection.id
                                    #Skeleton stores a raw id reference to the object for updating
                Skeleton.models[collection.id] = targetObj[name]

                _.each collection.models, (modelData, index) ->
                    newObj = targetObj[name]._add({}, {silent: silent})
                    process(newObj, modelData)  

        if data.models
            _.each data.models, (modelData, name) ->
                process(targetObj[name], modelData)

    process(@, data)

    return @