2015-10-12 3 views
3

У меня есть следующий код, который работает, когда я правильно добавляю виджет в (1,1), но когда я использую (row, col) as (2,2), он добавляет виджет в 1,2). Что я делаю не так?Gridster не добавляет виджеты, где я хочу

gridster = $(".gridster ul").gridster({widget_selector: "li", widget_margins: [5, 5], widget_base_dimensions: [120, 40], min_cols: 0, min_rows: 0, max_size_x: false, avoid_overlapped_widgets: true}).data('gridster'); 

gridster.add_widget('<li><div>'+docItem.description+'</div><div>'+docItem.vals+'</div></li>', 1, 1, docItem.col, docItem.row); 

Результирующий HTML выглядит следующим образом ...

<div class="gridster ready"> 
    <ul id="gridData" style="width: 260px; position: relative; height: 50px;"> 
     <li data-col="1" data-row="1" data-sizex="1" data-sizey="1" class="gs-w" style="display: list-item;"><div>Total</div><div>1</div></li> 
     <li data-col="2" data-row="1" data-sizex="1" data-sizey="1" class="gs-w" style="display: list-item;"><div>John</div><div>2</div></li> 
    </ul> 
</div> 

Я хотел проверить, что gridster добавить виджет, где когда-либо я хочу, а не в линейном дополнительном шаблоне.

EDIT: Функционирование, полный пример ниже в соответствии с запросом.

клиент/myCell.js

Template.cellular.created= function() { 
Session.set('idxX',0); 
Session.set('idxY',0); 
Session.set('gridInit', 0); 
currentFileId = "someId"; 
console.log("Setting file id"); 

Meteor.call('setFileId', currentFileId, function() { 
    console.log("published"); 
    if(Session.get('gridInit') == 0) { 
     gridster = $(".gridster ul").gridster({widget_selector: "li", widget_margins: [5, 5], widget_base_dimensions: [120, 40], min_cols: 0, min_rows: 0, max_size_x: false, avoid_overlapped_widgets: true}).data('gridster'); 
     Session.set('gridInit',1); 
    } 
    Meteor.subscribe("myCells"+currentFileId, function() { 
        cells = cellItems.find({owner: 1, myFileId: currentFileId}).fetch(); 
        console.log(cells); 

        cells.forEach(function(docItem, idx){ 

         console.log("inserting = " +idx + " item.row = "+docItem.row + " item.col = " + docItem.col); 
         //Blaze.renderWithData(Template.cells, docItem, $('#data').get(0)); 
         gridster.add_widget('<li><div>'+docItem.description+'</div><div>'+docItem.vals+'</div></li>', 1, 1, docItem.col, docItem.row); 
       }); 
      }); 
}); 
}; 

Template.cellular.events({ 
'keydown .newCellDesc': function (e, t) { 
    if (event.keyCode == 13 || event.keyCode == 9) { 
     $('.newCellFormula').focus(); 
     event.stopPropagation(); 
     return false; 
    } 
}, 
'keydown .newCellVal': function (e, t) { 
     if (event.keyCode == 13 || event.keyCode == 9) { 
      $('.newCellDesc').focus(); 
      event.stopPropagation(); 
      return false; 
     } 
}, 
'keydown .newCellFormula': function (e, t) { 
     if (event.keyCode == 13 || event.keyCode == 9) { 
      $('.newCellVal').focus(); 
      event.stopPropagation(); 
      return false; 
     } 
}, 
'click #newCellUse': function (e, t) { 

    $('#gridData').empty(); 

    if(Session.get('gridInit') == 0) { 
     gridster = $(".gridster ul").gridster({autogenerate_stylesheet: true, widget_selector: "li", widget_margins: [5, 5], widget_base_dimensions: [120, 40], min_cols: 0, min_rows: 0, max_size_x: false, avoid_overlapped_widgets: true}).data('gridster'); 
     Session.set('gridInit',1); 
    } 

    Session.set('idxX', Session.get('idxX') + 1); 
    Session.set('idxY', Session.get('idxY') + 1); 
    var idxX = Session.get('idxX'); 
    var idxY = Session.get('idxY'); 
    console.log("Adding new cell to cell list "); 

    if($('.newCellDesc').text().trim() != '' && $('.newCellVal').text().trim() != '' && $('.newCellFormula').text().trim() != '') { 

     Meteor.call('insertCell', "someId", {owner: 1, myFileId: currentFileId, description: $('.newCellDesc').text().trim(), vals: $('.newCellVal').text().trim(), formula: $('.newCellFormula').text().trim(), col: idxX, row: idxY}, function() { 

      console.log("updating gridster with data"); 
      Meteor.subscribe("myCells"+currentFileId, function() { 
        cells = cellItems.find({owner: 1, myFileId: currentFileId}).fetch();   
        console.log(cells); 

        cells.forEach(function(docItem, idx){ 

         console.log("inserting = " +idx + " item.row = "+docItem.row + " item.col = " + docItem.col); 
         //Blaze.renderWithData(Template.cells, docItem, $('#data').get(0)); 
         el = '<li><div>'+docItem.description+'</div><div>'+docItem.vals+'</div></li>' 
         gridster.add_widget(el, 1, 1, docItem.col, docItem.row); 
       }); 
      }); 
     }); 
    } 
    event.stopPropagation(); 
    return false; 
} 
}); 

клиент/myCell.css

.container { width: auto; } 

клиент/newCell.css

#newCell 
{ 
    width:400px; 
    height: 40px; 
    background-color: white; 
    border: transparent; 
} 

.newCellDesc 
{ 
    width:30%; 
    height: 40px; 
    background-color: white; 
    border: 0.5px solid black; 
    float: left; 
} 

.newCellVal 
{ 
    width:25%; 
    height: 40px; 
    background-color: white; 
    border: 0.5px solid black; 
    float: left; 
} 

.newCellFormula 
{ 
    width:30%; 
    height: 40px; 
    background-color: white; 
    border: 0.5px solid black; 
    float: left; 
} 

клиент/myCell.html

<body>{{> cellular}}</body> 

<template name="cellular"> 
<div id='cellPane'> 
    <div id='newCell'> 
     <div class='newCellDesc' contenteditable="true" display="block" placeholder="Description"> 
     </div> 
     <div class='newCellFormula' contenteditable="true" display="block" placeholder="Formula"> 
     </div> 
     <div class='newCellVal' contenteditable="true" display="block" placeholder="Value"> 
     </div> 
     <button id='newCellUse' class="btn-sm btn-primary" type="submit">Add</button> 
    </div> 
    <div id='data' class='container-fluid'> 
     <div class="gridster"> 
      <ul id="gridData"> 
      </ul> 
     </div> 
    </div> 
</div> 
</template> 

сервер/cell.js

var fileId; 
cellItems.allow({ 
    'insert': function (userId,doc) { 
    return true; 
    }, 
    'update': function (userId,doc) { 
     return true; 
    } 
}); 

Meteor.methods({ 
    setFileId: function (theId) { 
     console.log(theId); 
     fileId = theId; 
     Meteor.publish('myCells'+fileId, function(){ 
      console.log("using "+fileId + " to publish"); 
      return cellItems.find({owner: 1, myFileId: fileId}); 
     }); 
    }, 
    insertCell: function (fileId,item) { 
     console.log(item); 
     cellItems.insert(item); 
     console.log(cellItems.find({owner: 1, myFileId: fileId}).fetch()); 
     return true; 
    } 
}); 

LIB/collection.js

items = new Mongo.Collection("folders"); 

cellItems = new Mongo.Collection("cells"); 

currentFileId = null; 
myId = null; 
+1

Сетчатка выглядит как хороший плагин. Если вы создадите [mcve], я посмотрю. – JeremyK

ответ

1

Это much-requested функция для Gridster, но хорошие новости, есть a fix for it доступны в вилке.

Старый ducksboard repo Gridster был в состоянии покоя более года, но другие сопровождающие вмешались, чтобы объединить последние взносы. я настоятельно рекомендую the dsmorse fork of Gridster, и использовали его в своих проектах (и способствовало крошечное исправление к нему, никакого отношения к этому вопросу).

Вот main demo & download page для вилки dsmorse.

Среди других улучшений функций у этой вилки есть опция shift_widgets_up: false, которая предотвращает привязку виджетов к самому верхнему доступному положению в сетке. Играя с the demo этого немного, похоже, что это может быть не совсем безнаказанно, но это самое близкое, что я знаю, к чему вы спрашиваете.

+0

Есть ли там метеорный пакет? Мне нужно, чтобы он работал с метеоритом. – Ram

+2

Не то, чтобы я знал, но вы могли [сделать это] (http://stackoverflow.com/questions/10114526/how-to-build-a-meteor-smart-package)? – emackey

+0

Mucho спасибо! я смог сделать его локальным пакетом и добавить его, но выдает ошибку при запуске метеор. Вы можете помочь с этим? 'W20151019-18: 47: 04,928 (-4)? (STDERR) TypeError: Не удается прочитать свойство «fn» неопределенного значения 'W20151019-18: 47: 04.928 (-4)? (STDERR) в jquery.gridster.js: 118: 6' – Ram

Смежные вопросы