Marionette drop in new ItemView after every fetch not working - marionette

I am working with an app that after every collection.fetch, I need to drop in a random ad into the DOM. But, every time the collection fetches, and the ad is dropped in, it appears that the DOM is resetting itself instead of just appending new items to the overall collection container.
Here is the ItemView for the ad:
define(["marionette", "lodash", "text!ads/template.html", "eventer"],
function(Marionette, _, templateHTML, eventer) {
'use strict';
var AdsView = Marionette.ItemView.extend({
template: _.template(templateHTML),
ui: {
ad: '.ad'
},
initialize: function() {
this.listenTo(eventer, 'generate:new:ad', this.generateNewAd, this);
},
onShow: function() {
// Set add image onShow
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
},
generateNewAd: function(childView) {
var newAd = this.ui.ad.clone(),
element = childView.$el,
elementId = childView.model.get("id");
newAd.prop('src', '/ad/' + this.randomNumber());
$("#" + elementId).after(newAd);
},
randomNumber: function() {
return Math.floor(Math.random()*1000);
},
setUpAd: function() {
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
}
});
return AdsView;
});
CompositeView that holds the Products (I'm calling for a new ad after the collection is done syncing):
define(["marionette", "lodash", "text!fonts/products/template.html",
'fonts/products/item-view', 'fonts/products/model', 'eventer'],
function(Marionette, _, templateHTML, ProductItemView, ProductsModel, eventer) {
'use strict';
var ProductsView = Marionette.CompositeView.extend({
template: _.template(templateHTML),
childView: ProductItemView,
childViewContainer: '.items',
productsLimit: 150,
initialize: function() {
this.listenTo(eventer, 'sort:products', this.sortCollection, this);
this.listenTo(this.collection, 'sync', this.setupSync, this);
},
sortCollection: function(field) {
this.collection.sortByKey(field);
},
setupSync: function() {
this.setupWindowScrollListener();
this.adGeneration();
},
adGeneration: function() {
var child = this.children.last();
eventer.trigger('generate:new:ad', child);
},
productsEnd: function() {
eventer.trigger('products:end');
},
setupWindowScrollListener: function() {
var $window = $(window),
$document = $(document),
that = this,
collectionSize = that.collection.length;
if(collectionSize <= that.productsLimit) {
$window.on('scroll', _.throttle(function() {
var scrollTop = $window.scrollTop(),
wHeight = $window.height(),
dHeight = $document.height(),
margin = 200;
if(scrollTop + wHeight > dHeight - margin) {
eventer.trigger('fetch:more:products');
$window.off('scroll');
}
}, 500));
} else {
that.productsEnd();
}
},
});
return ProductsView;
});

From your previous question I noticed that you're passing { reorderOnSort: false } to your ProductsView. This will cause your CompositeView to re-render on a sort event. Since a 'sort' event is triggered by Collection.set(), you'll have to pass { reorderOnSort: true } to ensure that your CompositeView is not re-rendered after a fetch → set → sort.
Note: If your CompositeView defines a filter method and the children are filter'ed when new models are fetched, the CompositeView will re-render.

Related

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

Using server side true, datatables column search not working, but the global search works

I'm using datatables with server-side attribute true, the search work on global search, but not when I'm using column search. There isn't any error, the table is redrawn but the search not applied.
//index.blade.php
<script>
$('#filter-time-slot-submit').on('click', function() {
var table = $('#hide_show_column').DataTable({
'retrieve': true,
});
var timeSlot = $('#select2-chosen-2').text();
table
.columns(3)
.search(timeSlot)
.draw();
});
</script>
//table-advanced.js
var TableAdvanced = function () {
var initHideShowColumn = function () {
var table = $('#hide_show_column');
var tableWrapper = $('#hide_show_column_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper
var tableColumnToggler = $('#hide_show_column_column_toggler');
var tableHeaderRow = $('#table-header-row');
var columns = [];
var colName;
var ajaxUrl;
$('input[type="checkbox"]', tableColumnToggler).each(function(index, el) {
colName = $(el).attr('data-name');
columns.push({
"name": colName
});
$(el).attr("data-column", index);
if (colName.indexOf('.') > 0) {
colName = colName.substring(0, colName.indexOf('.'));
}
tableHeaderRow.append($('<th class="filter_' + colName + ' text-center">' + $(el).parent().parent().parent().text() + '</th>'));
});
columns.push({"name": ""});
tableHeaderRow.append($('<th class="text-center">Action</th>'));
if (typeof table.attr('data-url') !== 'undefined') {
ajaxUrl = table.data('url');
} else {
ajaxUrl = window.location.href;
}
table.on('init.dt', function () {
Index.init();
});
table.on('draw.dt', function () {
Index.draw();
});
var oTable = table.DataTable({
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "No data available in table",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"infoEmpty": "No entries found",
"infoFiltered": "(filtered from _MAX_ total entries)",
"lengthMenu": "Show _MENU_ entries",
"search": "Search:",
"zeroRecords": "No matching records found"
},
"columnDefs": [{
"orderable": false,
"targets": [-1]
}],
"columns": columns,
"aaSorting": [],
"lengthMenu": [
[10, 25, 50, 100, 250, 500, 1000, -1],
[10, 25, 50, 100, 250, 500, 1000, "All"] // change per page values here
],
"serverSide": true,
"processing": true,
"ajax": {
"url": ajaxUrl
}
});
/* modify datatable control inputs */
tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown
/* init hidden column*/
$('input[type="checkbox"]', tableColumnToggler).each(function(index, el) {
var checked = el.checked;
if (!checked) {
var column = oTable.column(index);
column.visible( ! column.visible() );
}
});
/* handle show/hide columns*/
$('input[type="checkbox"]', tableColumnToggler).change(function () {
/* Get the DataTables object again - this is not a recreation, just a get of the object */
var column = oTable.column($(this).attr("data-column"));
column.visible( ! column.visible() );
});
$('.form-filter-submit').on('click', function (e) {
e.preventDefault();
submitFilter(oTable);
});
$('.form-filter-reset').on('click', function (e) {
e.preventDefault();
resetFilter(oTable);
});
}
function submitFilter(table) {
var query = [];
var filterColumn;
var filterValue;
// get all typeable inputs
$('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])').each(function() {
if ($(this).val()) {
filterColumn = '__' + $(this).attr('name');
filterValue = $(this).val();
query.push(filterColumn + '=' + filterValue);
}
});
// // get all checkboxes
// $('input.form-filter[type="checkbox"]:checked', table).each(function() {
// the.addAjaxParam($(this).attr("name"), $(this).val());
// });
// // get all radio buttons
// $('input.form-filter[type="radio"]:checked', table).each(function() {
// the.setAjaxParam($(this).attr("name"), $(this).val());
// });
table.settings().ajax.url('?'+query.join('&'));
table.ajax.reload();
}
function resetFilter(table) {
table.settings().ajax.url(window.location.href).load();
}
return {
//main function to initiate the module
init: function () {
if (!jQuery().dataTable) {
return;
}
initHideShowColumn();
}
};
}();
I expect the table should be filtered by the search when I click a button, but the table shows all the data.
Any help will be greatly appreciated. Thank You.

Execute validation with button

I'm looking to execute the Handsontable validation on the click of a button instead of on cell change. Something like this: validateCells() (return bool isValid). This function doesn't seem to be working for me.
var
data = [],
container = document.getElementById('hot-Handsontable'),
save = document.getElementById('save'),
hidden = document.getElementById('hot-Handsontable-value'),
hot,
hotIsValid = true,
emailValidator;
emptyValidator = function(value, callback) {
callback(false);
};
hot = Handsontable(container, {
data: data,
minRows: 1,
minCols: 21,
maxCols: 21,
minSpareRows: 1,
stretchH: 'all',
colHeaders: ['Test'],
columns: [{data:'Test',allowInvalid:true, validator: emptyValidator}]
});
// exclude empty rows from validation
$('.title-block .united-alert a[href^=#Handsontable]').click(function() {
var href = $(this).attr('href');
var row = href.getIdIndex();
var prop = /([^__]*)$/.exec(href)[0];
hot.selectCellByProp(parseInt(row), prop);
return false;
});
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
var test = hot.validateCells(); // test is undefined
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
});
What you should be doing, instead of var test = hot.validateCells() is the following:
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
hot.validateCells(function(hotIsValid) {
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
})
});
Notice that validateCells takes a callback and returns undefined. This is why you see test as undefined. One other thing to note is that the callback is executed for every cell in your table so be careful with it.

Marionette CompositeView children.findByIndex not working as expected after collection sync

I have the following code that happens after a collection sync:
adGeneration: function() {
var child = this.children.findByIndex(this.children.length - 1);
console.log(child.model.toJSON());
eventer.trigger('generate:new:ad', child);
},
The problem I am running into, is that, after the first sync, the child element is a blank model:
First Time:
Object {id: "5-vp39kv3uiigxecdi", size: 26, price: "9.84", face: "( ⚆ _ ⚆ )"}
Every time after:
Object {length: 40, models: Array[41], _byId: Object, _listeningTo: Object, _listenId: "l14"…}
ProductsCollection
define(["backbone", "lodash", "fonts/products/model", "eventer"],
function(Backbone, _, ProductModel, eventer) {
'use strict';
var ProductsCollection = Backbone.Collection.extend({
model: ProductModel,
sort_key: 'price',
url: '/api/products',
offset: 0,
initialize: function() {
this.listenTo(eventer, 'fetch:more:products', this.loadMore, this);
},
comparator: function(item) {
return item.get(this.sort_key);
},
sortByKey: function(field) {
this.sort_key = field;
this.sort();
},
parse: function(data) {
return _.chain(data)
.filter(function(item) {
if(item.id) {
return item;
}
})
.map(function(item){
item.price = this.formatCurrency(item.price);
return item;
}.bind(this))
.value();
},
formatCurrency: function(total) {
return (total/100).toFixed(2);
},
loadMore: function() {
this.offset += 1;
this.fetch({
data: {
limit: 20,
skip: this.offset
},
remove: false,
success: function(collection) {
this.add(collection);
}.bind(this)
});
}
});
return ProductsCollection;
});
LayoutView that contains the View for the productions collection. The collection is fetched onShow of the layoutview
define(["marionette", "lodash", "text!fonts/template.html",
"fonts/controls/view", "fonts/products/view", "fonts/products/collection", "eventer"],
function(Marionette, _, templateHTML, ControlsView, ProductsView,
ProductsCollection, eventer) {
'use strict';
var FontsView = Marionette.LayoutView.extend({
regions: {
controls: '#controls',
products: '#products-list'
},
template: _.template(templateHTML),
initialize: function() {
this._controlsView = new ControlsView();
this._productsView = new ProductsView({
collection: new ProductsCollection({
reorderOnSort: false,
sort: false
})
});
this.listenTo(this._productsView.collection, 'sync', this.loading, this);
this.listenTo(eventer, 'fetch:more:products', this.loading, this);
this.listenTo(eventer, 'products:end', this.productsEnd, this);
},
onRender: function() {
this.getRegion('controls').show(this._controlsView);
this.getRegion('products').show(this._productsView);
this.loading();
},
onShow: function() {
this._productsView.collection.fetch({
data: {
limit: 20
}
})
},
productsEnd: function() {
this.loading();
this.$el.find('#loading').html("~ end of catalogue ~")
},
loading: function() {
var toggle = this.$el.find('#loading').is(':hidden');
this.$el.find('#loading').toggle(toggle);
}
});
return FontsView;
});
AdsView:
define(["marionette", "lodash", "text!ads/template.html", "eventer"],
function(Marionette, _, templateHTML, eventer) {
'use strict';
var AdsView = Marionette.ItemView.extend({
template: _.template(templateHTML),
ui: {
ad: '.ad'
},
initialize: function() {
this.listenTo(eventer, 'generate:new:ad', this.generateNewAd, this);
},
onShow: function() {
// Set add image onShow
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
},
generateNewAd: function(childView) {
var newAd = this.ui.ad.clone(),
element = childView.$el,
elementId = childView.model.get("id");
newAd.prop('src', '/ad/' + this.randomNumber());
$("#" + elementId).after(newAd);
},
randomNumber: function() {
return Math.floor(Math.random()*1000);
},
setUpAd: function() {
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
}
});
return AdsView;
});
I think your problem is in the ProductsCollection.loadMore method. There, in the success callback to your fetch you do,
function(collection) { this.add(collection); }
What's happening behind the scenes is that before your success callback is invoked, Backbone will first run Collection.set() on your data. By default, inside set your data will be parsed into a array of models returned by ProductsCollection.parse and if any new models are found they will be add'ed to your existing collection (note that unless you pass { remove: false } to your fetch options, models in your collection which are not in your last fetch will be removed. See Collection.set)
So, what happens when you do the fetch in loadMore, which is called after the first fetch, Backbone will first add all the models from the server (that are returned from ProductsCollection.parse) and then invoke the success callback of your fetch, which, essentially does one last add. And what it's add'ing is the ProductsCollection instance. Not collection.models, an array of models, rather a Backbone object that has a property models that holds a raw array of models. Hence, the strange output:
Object {length: 40, models: Array[41], _byId: Object, _listeningTo: Object,
_listenId: "l14"…}
Simply remove that success callback (which is unnecessary) and the last child view of your ProductsView should be the view rendered from the last model returned.

Trigger sort method from an event in Backbone.js

I have a Backbone.js project which uses a comparator function defined in the collection. It sorts items when the page is refreshed, but I am trying to get it to sort when a button is clicked instead of on page refresh. Here is my code:
var Thing = Backbone.Model.extend({
defaults: {
title: 'blank',
rank: ''
}
});
var ThingView = Backbone.View.extend({
className: 'thingClass',
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %> Rank:<%= rank %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function () {
console.log('deleted');
this.model.destroy();
this.remove();
},
editItem: function () {
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function () {
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({
title: editTitle
});
this.$el.html(this.template(this.model.toJSON()));
},
render: function () {
var attributes = this.model.toJSON();
//console.log (attributes);
this.$el.append(this.template(attributes));
return this;
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name"),
comparator: function(thing) {
return thing.get('rank');
},
});
var thingsList = new ThingsList;
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem',
'click #sort': 'sortItems',
},
initialize: function () {
thingsList.fetch();
thingsList.toJSON();
this.render();
this.collection.on("add", this.renderThing, this);
this.collection.on("reset", this.clearRender, this);
},
insertItem: function (e) {
newTitle = $('#new-item').val();
newRank = $('#rank').val();
newThing = new Thing({
title: newTitle,
rank: newRank
});
this.collection.add(newThing);
newThing.save();
console.log(this.collection.length);
},
sortItems: function (e) {
console.log('clicked sort button');
this.collection.sort();
this.$el.detach('.item');
},
render: function () {
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function (items) {
var thingView = new ThingView({
model: items
});
this.$el.append(thingView.render().el);
},
clearRender: function () {
console.log('clear render called')
_.each(this.collection.models, function (items) {
//this.remove();
this.$el.remove(".thingClass")
this.renderThing(items);
}, this);
},
test: function (items) {
console.log('test worked');
},
});
var thingsListView = new ThingsListView({
collection: thingsList
});
Are you sure your collection isn't resorting itself? keep in mind that the order of the models in the collection won't change the order of how they appear on the page if they are already rendered.
I'm guessing that what you are trying to do is resort the items that have already been rendered, to do so you would need re-render your collection. If you are going to do so I would recommend that you cache your views and on a sort detach the associated element from the DOM and reattach them in the correct order.
As an example
var ThingsListView = Backbone.View.extend({
_views: {},
initialize: function () {
this.collection.bind('add', this.add, this);
this.collection.bind('reset', this.render, this); //sort triggers a reset
},
add: function (thing) {
var view = new ThingView({model: thing});
this._views[thing.cid] = view; //use client id of model as key for the views cache
this.$el.append(view.render().el);
},
render: function() {
$('li, this.$el).detach(); //detach so that bound events aren't lost
_.each(this.collection.models, function(thing) {
this.$el.append(this.views[thing.cid].el); //get view from cache
},this);
},
sort: function() {
this.collection.sort();
}
}
})
(a couple of differences from my example code and yours I'm assuming here that the collection view has a 'el' referring to a container 'ul', I also don't show how your triggering the sort (basically something like thingListView.sort();)
Edit: It might not be so obvious from the example code I posted, so I should have mentioned to begin with what #Deeptechtons said that when you sort a collection it triggers a reset event
Edit2: If your not interested in caching your views, then the easiest way to remove your current views would probablly be to add a class to the rendered div
var ThingView = Backbone.View.extend({
className: 'thingClass',
//rest of your thingViewCode
Then in your clearRender method just add $(".thingClass", this.$el).remove(); to the beginning of the method.

Resources