适当地折叠和重建嵌套模型

Properly collapse and rebuild nested models?

本文关键字:重建 嵌套 模型 折叠      更新时间:2023-09-26

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

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

现在我明白了这一点,我需要找出最好的方法来折叠和重建包含嵌套集合/模型的骨干模型。

任何指示将是伟大的,谢谢!

您可以定义在视图的数据更改时呈现什么和不呈现什么。你可以确保绑定到"change"的事件只呈现你想要的内容。您还可以绑定到事件,仅针对某些属性的更改。你不必只用一个包罗万象的"change"。

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

我决定使用我从Henrik Joreteg的示例中重建的CoffeeScript中的这个解决方案。

# 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 @