与Gridster和Knockout绑定的小部件

时间:2013-10-23 18:03:55

标签: javascript jquery knockout.js gridster

我是Javascript的新手,并尝试将Gridster与Knockout一起使用。我有一个包含项目的数据库,我使用knockout foreach将它们绑定到UL。 UL采用Gridster库设计。除非我尝试通过viewmodel中的ObservableArray向UL添加其他元素,否则一切都很有效。

有谁能帮我理解这里的操作范围和顺序?感觉就像Gridster库没有为新的小部件做样式。

This jsfiddle显示了该问题的工作演示。请注意,当您双击窗口小部件时,它会创建一个新窗口小部件,但不会将其放在网格中。相反,它只是背后隐藏。

这是HTML

   <div class="gridster">
        <ul data-bind="foreach: myData">
            <li data-bind="attr:{

              'data-row':datarow,
              'data-col':datacol,
              'data-sizex':datasizex,
              'data-sizey':datasizey

        },text:text, doubleClick: $parent.AddOne"></li>
        </ul>
    </div>

这是Javascript

//This is some widget data to start the process
var gridData = [ {text:'Widget #1', datarow:1, datacol:1, datasizex:1, datasizey:1},
    {text:'Widget #2', datarow:2, datacol:1, datasizex:1, datasizey:1},
    {text:'Widget #3', datarow:1, datacol:2, datasizex:1, datasizey:1},
    {text:'Widget #4', datarow:2, datacol:2, datasizex:1, datasizey:1}];

// The viewmodel contains an observable array of widget data to be 
//    displayed on the gridster
var viewmodel = function () {

    var self = this;
    self.myData = ko.observableArray(gridData);
    //AddOne adds an element to the observable array 
    //   (called at runtime from doubleClick events)
    self.AddOne = function () {
        var self = this;
        myViewModel.myData.push({
            text: 'Widget Added After!',
            datarow: 1,
            datacol: 1,
            datasizex: 1,
            datasizey: 1
        });
    };

};


var myViewModel = new viewmodel();
ko.applyBindings(myViewModel);

$(".gridster ul").gridster({
    widget_margins: [5, 5],
    widget_base_dimensions: [140, 140]
});

4 个答案:

答案 0 :(得分:2)

以下是JSfiddle中的完整示例。在这里,我只突出了删除功能

self.deleteOne = function (item) {
    console.log(item);
    var widget = $("#" + item.id);
    console.log(widget);
    var column = widget.attr("data-col");
    if (column) {
        console.log('Removing ');
        // if this is commented out then the widgets won't re-arrange
        self.gridster.remove_widget(widget, function(){
            self.myData.remove(item);
            console.log('Tiles: '+self.myData().length);                
        });
    }
};

从可观察数组中删除元素的工作是在remove_widget回调中完成的。请参阅gridster的documentation。因此,删除窗口小部件之前执行的removeGridster挂钩不再需要执行实际的remove_widget调用。

答案 1 :(得分:1)

这是一个可行的解决方案,我认为更符合MVVM模式:

http://jsfiddle.net/Be4cf/4/

//This is some widget data to start the process
var gridData = [
    {id: "1", text:'Widget #1', datarow:1, datacol:1, datasizex:1, datasizey:1},
    {id: "2", text:'Widget #2', datarow:1, datacol:2, datasizex:2, datasizey:1},
    {id: "3", text:'Widget #3', datarow:1, datacol:4, datasizex:1, datasizey:1},
    {id: "4", text:'Widget #4', datarow:2, datacol:1, datasizex:1, datasizey:2}];

// The viewmodel contains an observable array of widget data to be 
//    displayed on the gridster
var viewmodel = function () {

    var self = this;
    self.myData = ko.observableArray(gridData);
    self.nextId = 5;
    self.gridster = undefined;

    // AddOne adds an element to the observable array.
    // Notice how I'm not adding the element to gridster by hand here. This means  
    // that whatever the source of the add is (click, callback, web sockets event), 
    // the element will be added to gridster.
    self.addOne = function () {
    myViewModel.myData.push({
            text: 'Widget Added After!',
            datarow: 1,
            datacol: 1,
            datasizex: 1,
            datasizey: 1,
            id: self.nextId++
        });
    };

    // Called after the render of the initial list.
    // Gridster will add the existing widgets to its internal model.
    self.initializeGridster = function() {
        self.gridster = $(".gridster ul").gridster({
            widget_margins: [5, 5],
            widget_base_dimensions: [140, 140]
        }).data('gridster');
    };

    // Called after the render of the new element.
    self.addGridster = function(data, object) {
        // This bypasses the add if gridster has not been initialized.
        if (self.gridster) {
            var $item = $(data[0].parentNode);

            // The first afterRender event is fired 2 times. It appears to be a bug in knockout.
            // I'm pretty new to knockout myself, so it might be a feature too! :)
            // This skips the second call from the initial fired event.
            if (!$item.hasClass("gs-w"))
            {
                // This removes the binding from the new node, since gridster will re-add the element.
                ko.cleanNode(data[0].parentNode);
                // Adds the widget to gridster.
                self.gridster.add_widget($item);
                // We must update the model with the position determined by gridster
                object.datarow = parseInt($item.attr("data-row"));
                object.datacol = parseInt($item.attr("data-col"));
            }
        }
    };
};

var myViewModel = new viewmodel();
ko.applyBindings(myViewModel);

我仍然需要考虑删除和移动事件(gridster中的移动应该在viewmodel中更新项目的x和y值)。我昨天开始使用淘汰赛,所以任何帮助都会受到赞赏。

我找不到最新版gridster的cdn。 JSFiddle指向我在Azure中添加的临时网站,我会将其保留几天,但随时可以使用您自己的链接进行更新。

/ ------------------------------ UPDATE --------------- ------------------- /

我已经更新了我的代码以支持删除和移动小部件(http://jsfiddle.net/Be4cf/11/)但是有一个小警告:在调用beforeRemove事件之前,敲除清除jquery数据的开放问题(https://github.com/knockout/knockout/issues/1130) 。这会导致gridster崩溃,因为移动其他项目所需的数据保存在数据元素中。解决方法可能是保留数据的副本并稍后将其重新添加到元素中,但我选择了懒惰的方式并在淘汰赛中评论了违规行。

答案 2 :(得分:0)

将class =“gs_w”添加到gridster中的ur li它应该可以工作

答案 3 :(得分:0)

您应该执行以下操作。调用addNewGridElement - 使用渲染的DOM元素,这在Gridster的情况下很重要,因为gridster.add_widget接受DOM元素作为其第一个参数 - 一旦你向Knockout observable添加了一些东西。在此之后,只需将domNode添加到Gridster即可。

<强> view.html:

   <div class="gridster">
        <ul data-bind="foreach: { myData, afterAdd: $root.addNewGridElement }">
            <li data-bind="attr:{

              'data-row':datarow,
              'data-col':datacol,
              'data-sizex':datasizex,
              'data-sizey':datasizey

        },text:text, doubleClick: $parent.AddOne"></li>
        </ul>
    </div>

<强> view.js:

self.addNewGridElement = function (domNode, index, newTile) {
    // Filter non li items - this will remove comments etc. dom  nodes.
    var liItem = $(domNode).filter('li');
    if ( liItem.length > 0 ) {
        // Add new Widget to Gridster
        self.gridster.add_widget(domNode, newTile.x, newTile.y, newTile.row, newTile.col);
    }
};