Backbone sort collections by click on non template elements - javascript

I want to sort my backbone collections by clicking non backbone template elements
In brief , i have 2 Sorting options named "Sort by date" and "Sort by name". when i click these elements i need to sort my collection in my backbone view
View template :
<ul>
<li>Sort By date</li>
<li>Sort By name</li>
</ul>
<script type="foo/bar" id='videos-thumbnail'>
<div class="col-md-4">
<div class="video-thumbnail-item">
<div style="background-image:url(recenty_added/recentlyadded2.jpg);" class="video-thumbnail"> </div>
<div class="video-details">
<div class="video-title text-purple uppercase"><%= title %></div>
<div class="video-date"><%= date %></div>
</div>
<div class="video-thumbnail-checkbox"> <span class="custom-checkbox">
<input type="checkbox" class="playlist-checkbox" name="addto-playlist[]">
</span>
<% if (is_rights_managed== true) { %>
<div class="checkbox-label-light">RM</div>
<% } else {%>
<div class="checkbox-label-light"></div>
<% } %>
</div>
<div class="video-thumbnail-options"> <span title="Download" class="option-parts"> <i class="fa fa-download"></i> </span> <span title="Edit" class="option-parts"> <i class="fa fa-pencil"></i> </span> <span title="More Information" class="option-parts"> <i class="fa fa-info-circle"></i> </span> <span title="View Details" class="option-parts"> <i class="fa fa-search"></i> </span> <span title="Add to Clipbins" class="option-parts"> <i class="fa fa-folder-open"></i> </span> <span title="Add to Cart" class="option-parts"> <i class="fa fa-cart-plus"></i> </span> <span title="Contact me about this Clip" class="option-parts"> <i class="fa fa-envelope"></i> </span> </div>
</div>
</div>
</script>
<div class="row" id="thumbnail_target"> </div>
App :
//backbone & underscore
$(function() {
var Videos = Backbone.Model.extend();
var VideoList = Backbone.Collection.extend({
model: Videos,
url: 'https://api.myjson.com/bins/4mht3'
});
var videos = new VideoList();
var VideoView = Backbone.View.extend({
el: "#thumbnail_target",
template: _.template($('#videos-thumbnail').html()),
render: function(eventName) {
_.each(this.model.models, function(video){
var videoTemplate = this.template(video.toJSON());
$(this.el).append(videoTemplate);
}, this);
return this;
},
});
var videosView = new VideoView({model: videos});
videos.fetch({
success: function() {
videosView.render();
videoslistView.render();
}
});
});
Am newbie to backbone and underscore, am not sure how to make this work
Example fiddle : Fiddle

Since you have access to collection outside view, you can simply use jquery to bind an event handler for the <li>, which updates the collections comparator and sorts it. Then have the view re-render itself when a sort event occurs on the collection.
for the demo I'm using string and number types of sort attributes so that I can directly set it as comparator. You should write a custom comparator function that handles sorting based on different types of arguments like string, number, date etc. Updated fiddle
//backbone & underscore
$(function() {
var Videos = Backbone.Model.extend();
var VideoList = Backbone.Collection.extend({
model: Videos,
url: 'https://api.myjson.com/bins/4mht3'
});
var videos = new VideoList();
var VideoListView = Backbone.View.extend({
el: "#thumbnail_target",
template: _.template($('#videos-thumbnail').html()),
initialize: function() {
this.listenTo(this.collection, 'sort', this.render);
},
render: function(eventName) {
this.$el.empty();
_.each(this.collection.models, function(video) {
var videoTemplate = this.template(video.toJSON());
this.$el.append(videoTemplate);
}, this);
return this;
},
});
var videosView = new VideoListView({
collection: videos
});
videos.fetch({
success: function(collection) {
videosView.render();
}
});
$('#sortBy').on('click', 'li', function() {
var category = $(this).text().split('Sort By ')[1];
videos.comparator = category;
videos.sort();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<ul id="sortBy">
<li>Sort By average</li>
<li>Sort By title</li>
</ul>
<script type="foo/bar" id='videos-thumbnail'>
<div class="col-md-4">
<div class="video-thumbnail-item">
<div style="background-image:url(recenty_added/recentlyadded2.jpg);" class="video-thumbnail"></div>
<div class="video-details">
<div class="video-title text-purple uppercase">
<%=t itle %>
</div>
<div class="video-date">
<%=d ate %>
</div>
</div>
<div class="video-thumbnail-checkbox"> <span class="custom-checkbox">
<input type="checkbox" class="playlist-checkbox" name="addto-playlist[]">
</span>
<% if (is_rights_managed==t rue) { %>
<div class="checkbox-label-light">RM</div>
<% } else {%>
<div class="checkbox-label-light"></div>
<% } %>
</div>
<div class="video-thumbnail-options"> <span title="Download" class="option-parts"> <i class="fa fa-download"></i> </span> <span title="Edit" class="option-parts"> <i class="fa fa-pencil"></i> </span> <span title="More Information" class="option-parts"> <i class="fa fa-info-circle"></i> </span>
<span
title="View Details" class="option-parts"> <i class="fa fa-search"></i>
</span> <span title="Add to Clipbins" class="option-parts"> <i class="fa fa-folder-open"></i> </span> <span title="Add to Cart" class="option-parts"> <i class="fa fa-cart-plus"></i> </span> <span title="Contact me about this Clip" class="option-parts"> <i class="fa fa-envelope"></i> </span>
</div>
</div>
</div>
</script>
<div class="row" id="thumbnail_target"></div>

Looks like you want global vent for in-app events
$(function() {
var channel;
channel = _.extend({}, Backbone.Events);
$('.some-sort-dy-date-element').on('click', function() {
channel.trigger('app:sort', {sortBy: 'date'});
});
$('.some-sort-dy-name-element').on('click', function() {
channel.trigger('app:sort', {sortBy: 'name'});
});
// rest logic
});
Your VideoList collection should listen to channel event like that (example for initialize):
var VideoList = Backbone.Collection.extend({
initialize: function initialize() {
this.listenTo(channel, 'app:sort', function someSortLogic() {
this.trigger('your.app.ns.videos.SORTED');
});
}
});
var VideoView = Backbone.View.extend({
initialize: function initialize() {
this.listenTo(this.collection, 'your.app.ns.videos.SORTED', this.render);
}
});

Related

Problem with creating an edit box in Vue.js

Well, I have a problem when creating fields for data editing. The problem is that when editing, all fields with the product name are activated instead of one specific. I know the problem is because I only have one variable responsible for enabling the edit box, but creating more variables will not solve the problem because then there may be thousands of such records.
HTML:
<ul>
<li v-for="product in products" class="single-product" v-bind:key="product.id_product">
<i style="color:#df4a49;padding:5px;" class="fa-solid fa-xmark fa-xl" #click="deleteProduct(product.id_product)"></i>
<p class="product-name"><i #click="enableEditing(product.name)" class="fas fa-edit" style="color:#0575ff;padding-right:5px;"></i>
<span v-if="!editing">{{product.name}}</span> <span v-if="editing"> <input v-model="tempValue" class="input"/>
<button #click="disableEditing"> Edit</button>
<button #click="saveEdit"> Save</button>
</span>
</p>
<span class="product-localization"><span><i class="fas fa-edit" style="color:#0575ff;padding-right:5px;"></i>Lokalizacja: </span>{{produkt.lokalizacja}}</span> <span class="product-key"><span><i class="fas fa-edit" style="color:#0575ff;padding-right:5px;"></i>Klucz: </span>{{product.key}}</span>
<hr />
</li>
</ul>
Data:
editing:false,
tempValue: null,
methods:
enableEditing: function(tempProductName){
this.tempValue = tempProductName;
this.editing=true;
},
disableEditing: function(){
this.tempValue = null;
this.editing = false;
},
saveEdit: function(){
this.value = this.tempValue;
this.disableEditing();
}

Call action on button outside function

I wrote a script where I add items to individual sections on the page. I will show you this by the example of one particular section. The problem appears with the c-grid-box, which is responsible for the fadeOut of the parent div. The anonymous function responsible for this action must be called outside of the diva addition function (otherwise I would have to add a function to each call that misses the target). For this I wrote something like this, although it still does not work - what could be the reason here?
function showModal(type) {
switch(type) {
case "title":
$(".overlay").fadeIn("slow");
$("#modal-inputs").html('<input type="text" placeholder="Title..." class="param-title" name="param-title" /><input type="text" placeholder="Description..." class="param-description" name="param-description" /><input type="submit" class="add-btn" id="insert-title" value="Insert" />');
break;
}
}
$("#add-text").on("click", function() {
showModal("title");
$("#insert-title").on("click", function() {
title = $(".param-title").val();
description = $(".param-description").val();
$('#section-title').append('<div class="grid-1-5"><div class="grid_box">Delete</i><p class="grid-box-title">'+title+'</p><p>'+description+'</p></div></div>');
$(".overlay").fadeOut("slow");
});
});
$(".grid_box").on("click", ".c-grid-box", function() {
alert("foo bar");
});
.overlay {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-text">
<i class="fa fa-align-justify" aria-hidden="true"></i>
<p>Add <i class="fa fa-angle-right" aria-hidden="true"></i></p>
</button>
<section class="add-box" id="section-title">
</section>
<div class="overlay">
<div class="modal-box">
<p class="modal-title"><i class="fa fa-cogs" aria-hidden="true"></i>Settings
<i class="fa fa-times" aria-hidden="true"></i>
</p>
<div id="modal-inputs">
</div>
</div>
</div>

Foreach: Toggle each icon - KnockoutJS

I am trying to toggle the plus symbol to minus sign, once after immediately that section get clicked and expanded. Following the code I have tried.
<div>
<ul style="list-style: none">
<li data-bind="foreach: model">
<div id="panelHeading">
<i class="fa fa-plus" style="padding-right: 5px;">+</i>
<span data-bind="text: Main"></span>
</div>
<div id="panelContent" data-bind="if: show">
<ul id="clustersList" data-bind="foreach: Sub" style="list-style: none">
<li><span style="padding-left: 20px;" data-bind="text: $data"></span></li>
</ul>
</div>
</li>
</ul>
</div>
=== JS ====
var viewModel = function() {
var self = this;
self.model = ko.observableArray([{
Main: "Main1",
Sub: ["hello", "hi"],
show: ko.observable(false)
}, {
Main: "Main2",
Sub: ["one", "two"],
show: ko.observable(false)
}]);
self.toggleShow = function (item) {
$('this a').find('i').toggleClass('fa fa-plus fa fa-minus');
var index = self.model.indexOf(item);
if (item.show())
self.model()[index].show(false);
else
self.model()[index].show(true);
}
}
ko.applyBindings(new viewModel());
Please check my Fiddle here.
Any suggestion would be helpful.
Just change your HTML to apply the correct style based on the current value of show:
<i class="fa" data-bind="css: { 'fa-plus': !show(), 'fa-minus': show() }"></i>
And in your JS:
self.toggleShow = function (item) {
item.show(!item.show());
};
See Fiddle

autocomplete search in ng-repeat in angularjs?

I my code i have 3 ng-repeats based on key press event value i am getting data from service and iam consuming
my html code is:
<div class="input-group" ng-controller="sidemenu">
<input class="form-control" placeholder="Enter location, builder or project" ng-model="NodeId_1" autofocus ng-keyup="getValue($event.keyCode)"/>
<div class="search-datalist" ng-if="showsearch">
<ul ng-if="resultOfBuldDet.length>0">
<span class="result-hd">Builders</span>
<li ng-repeat="bud in resultOfBuldDet" ng-class="{active :2}" ng-click="searchFilter(bud)"><i class="fa fa-map-marker"></i> {{bud.builders_name}}</li>
</ul>
<ul ng-if="resultOfPropDet.length>0">
<span class="result-hd">Properties</span>
<li ng-repeat="prop in resultOfPropDet" ng-click="searchFilter(prop)"><i class="fa fa-map-marker"></i> {{prop.property_name}} ,{{prop.hp_city.city_name}},{{prop.hp_location.location_name}} </li>
</ul>
<ul ng-if="resultOfCityDet.length>0">
<span class="result-hd">cities</span>
<li ng-repeat="city in resultOfCityDet" ng-click="searchFilter(city)"><i class="fa fa-map-marker"> </i> {{city.city_name}}</li>
</ul>
<ul ng-if="resultOfLocaDet.length>0">
<span class="result-hd">Location</span>
<li ng-repeat="loc in resultOfLocaDet" ng-click="searchFilter(loc)"><i class="fa fa-map-marker"></i> {{loc.location_name}},{{loc.hp_city.city_name}}</li>
</ul>
<ul ng-if="resultOfSubLocaDet.length>0">
<span class="result-hd">sub Location</span>
<li ng-repeat="subloc in resultOfSubLocaDet" ng-click=" searchFilter(subloc)"><i class="fa fa-map-marker"></i> {{subloc.sub_location_name}},{{subloc.hp_location.location_name}},{{subloc.hp_location.hp_city.city_name}}</li>
</ul>
</div>
</div>
my controller js code:
sidemenu.controller('sidemenu', ['$scope', '$rootScope', 'allServices'
function(a, b,e) {
a.getValue = function(key) {
if (key == 8 && a.NodeId_1.length <= 2) {
a.resultOfPropDet = "";
a.resultOfBuldDet = "";
a.resultOfLocaDet = "";
a.resultOfCityDet = "";
a.resultOfSubLocaDet = "";
}
if (a.NodeId_1.length > 2) {
e.searchList(a.NodeId_1).then(function(result) {
a.resultOfPropDet = result.data.resultOfPropDet;
a.resultOfBuldDet = result.data.resultOfBuldDet;
a.resultOfLocaDet = result.data.resultOfLocaDet;
a.resultOfCityDet = result.data.resultOfCityDet;
a.resultOfSubLocaDet = result.data.resultOfSubLocaDet;
a.showsearch = true;
}, function(error) {
});
}
}
});
so when i am moving up and down arrows in keyboard.how to highlight the particular rows and trigger the particular function
like this

Knockout click binding with mapping plugin

I am trying to use the click binding to increment and subtract a value in a text binding by one. I am not sure how to reference myNumber.
html:
<a data-bind="click: increment">
<i class="fa fa-chevron-up"> </i>
</a>
<div data-bind="text: myNumber"></div>
<a data-bind="click: subtract">
<i class="fa fa-chevron-down"> </i>
</a>
js:
<script type="text/javascript">
function increment(result){
result.myNumber ++;
}
function subtract(result){
result.myNumber --;
}
$.getJSON("/app/api/", function(result) {
function viewModel() {
return ko.mapping.fromJS(result);
};
ko.applyBindings(new viewModel());
})
.error(function () { alert("error"); });
</script>
You don't increment an observable as if it were a number. It is a setter/getter.
Also, the functions you bind need to be part of the viewmodel. You can do that inside your getJSON callback before applyBindings.
vm = {
myNumber: ko.observable(3),
increment: function(result) {
result.myNumber(result.myNumber() + 1);
},
subtract: function(result) {
result.myNumber(result.myNumber() - 1);
}
};
ko.applyBindings(vm);
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<a href="#" data-bind="click: increment">
<i class="fa fa-chevron-up"> </i>
</a>
<div data-bind="text: myNumber"></div>
<a href="#" data-bind="click: subtract">
<i class="fa fa-chevron-down"> </i>
</a>

Categories

Resources