error in using angular material md-autocomplete - angularjs

i am using angular material autocomplete.i am getting error when click on the autocomplete text box.
TypeError: Cannot read property 'then' of undefined
at me (angular-material.min.js:13)
at ve (angular-material.min.js:13)
at e.q [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.js:15152), <anonymous>:4:295)
at e (angular.js:26673)
at b.$eval (angular.js:17958)
at b.$apply (angular.js:18058)
at HTMLInputElement.<anonymous> (angular.js:26678)
at HTMLInputElement.dispatch (jquery.min.js:3)
at HTMLInputElement.r.handle (jquery.min.js:3)
here is my controller.
(function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$location', '$rootScope', '$scope', '$mdMedia', '$mdDialog'];
function MenuController($location, $rootScope, $scope, $mdMedia, $mdDialog) {
$scope.headtext = "This is header";
function initController() {
}
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
// ******************************
// Internal methods
// ******************************
/**
* Search for repos... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.repos.filter( createFilterFor(query) ) : self.repos,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `components` list of key/value pairs
*/
function loadAll() {
var repos = [
{
'name' : 'Angular 1',
'url' : 'https://github.com/angular/angular.js',
'watchers' : '3,623',
'forks' : '16,175',
},
{
'name' : 'Angular 2',
'url' : 'https://github.com/angular/angular',
'watchers' : '469',
'forks' : '760',
},
{
'name' : 'Angular Material',
'url' : 'https://github.com/angular/material',
'watchers' : '727',
'forks' : '1,241',
},
{
'name' : 'Bower Material',
'url' : 'https://github.com/angular/bower-material',
'watchers' : '42',
'forks' : '84',
},
{
'name' : 'Material Start',
'url' : 'https://github.com/angular/material-start',
'watchers' : '81',
'forks' : '303',
}
];
return repos.map( function (repo) {
repo.value = repo.name.toLowerCase();
return repo;
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
})();
This is my html
<md-content layout-padding layout="column">
<form ng-submit="$event.preventDefault()">
<md-autocomplete ng-disabled="ctrl.isDisabled"
md-no-cache="ctrl.noCache"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.name"
md-min-length="0"
placeholder="Pick an Angular repository"
md-menu-class="autocomplete-custom-template">
<md-item-template>
<span class="item-title">
<md-icon md-svg-icon="img/icons/octicon-repo.svg"></md-icon>
<span> {{item.name}} </span>
</span>
<span class="item-metadata">
<span class="item-metastat">
<strong>{{item.watchers}}</strong> watchers
</span>
<span class="item-metastat">
<strong>{{item.forks}}</strong> forks
</span>
</span>
</md-item-template>
</md-autocomplete>
</form>
</md-content>
i cannot trace this error please help.

You're not instantiated the selected items.
self.selectedItem = [];

Related

Error while implementing md-autocomplete in angular

After executing the list in md-autoComplete. I am getting this error while searching. I have given controller name as ctrl and included the $timeout, $q, $log, attaching html and js file.
Please let me know how to fix it. Thanks in advance.
error
ionic.bundle.js:26794 TypeError: Cannot read property 'indexOf' of
null
at filterFn (http://localhost:8100/js/guest-controller.js:102:31)
at Array.filter (native)
at Object.querySearch (http://localhost:8100/js/guest-
controller.js:60:41)
at fn (eval at compile
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:27638:15),
<anonymous>:4:344)
at Scope.$eval
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:30395:28)
at de
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:11563)
at he
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:12420)
at
https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:8834
at processQueue
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:29127:28)
html file
<div class="form_element_grid auto_fill_info">
<label>Company Name</label>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="true"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.display"
md-min-length="0"
placeholder="Enter Company Name" required/>
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
Js file
var self = this;
$scope.guestDetails = guestData.data;
self.searchText = '';
self.simulateQuery = false;
self.isDisabled = false;
// list of `state` value/display objects
self.states = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
self.states= loadAll();
}
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.states.filter( createFilterFor(query)
) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); },
Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `states` list of key/value pairs
*/
function loadAll() {
var deliverycomp = $scope.guestDetails;
console.log(deliverycomp);
return deliverycomp.map( function (state) {
return {
value: state.guestId,
display: state.guestName
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = query;
return function filterFn(state) {
return (state.display.indexOf('lowercaseQuery') === 0);
};
}

md-autocomplete giving error on .then function

I am not able to use angularjs md-autocomplete directive. Please let me know where is the issue.
TypeError: Cannot read property 'then' of undefined
at de (angular-material.min.js:13)
at he (angular-material.min.js:13)
at e.B [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:415)
at b (angular.min.js:125)
at e (angular.min.js:272)
at b.$eval (angular.min.js:144)
at b.$apply (angular.min.js:145)
at HTMLInputElement.<anonymous> (angular.min.js:272)
I get this error when I opens md-autocomplete
TypeError: Cannot read property 'filter' of undefined
at DeliveryCtrl.querySearch (DeliveryCtrl.js:81)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:416)
at b (angular.min.js:125)
at n.$eval (angular.min.js:144)
at de (angular-material.min.js:13)
at he (angular-material.min.js:13)
at e.B [as focus] (angular-material.min.js:13)
at fn (eval at compile (angular.min.js:230), <anonymous>:4:415)
at b (angular.min.js:125)
at e (angular.min.js:272)
here is my controller
(function() {
'use strict';
RLabs.controller('DeliveryCtrl', DeliveryCtrl);
function DeliveryCtrl($timeout, $q, $log, $http, $scope, resto_info, base_url) {
$scope.delivery_areas = [];
$scope.fun1 = function() {
$scope.fun2().then(function(data) {
console.log("after call to fun2"); // execute before fun2
var myArray = data;
var myString = JSON.stringify(myArray.join(', '));
console.log(myString);
console.log(myArray);
return myString.split(/, +/g).map(function(state) {
return {
value: state.toLowerCase(),
display: state
};
});
});
}
$scope.fun2 = function() {
var deferred = $q.defer();
$http({
url: base_url.base_url + 'profile-load',
method: "POST",
data: {
"profile_id": resto_info.profile_id,
"api_key": resto_info.api_key,
"app_version": resto_info.app_version,
"request_operation": "get_delivery_area_data"
}
}).success(function(response) {
console.log(response);
console.log(response.response.location[0].delivery.areas);
$scope.delivery_areas = response.response.location[0].delivery.areas;
console.log($scope.delivery_areas);
deferred.resolve(response.response.location[0].delivery.areas);
}).error(function() {
deferred.resolve(null);
});
return deferred.promise;
}
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.states = $scope.fun1();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
alert("Sorry! You'll need to create a Constitution for " + state + " first!");
}
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function() {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
}})();
and here is my html
<div ng-controller="DeliveryCtrl as ctrl" layout="column" ng-cloak>
<md-content class="md-padding">
<form ng-submit="$event.preventDefault()">
<p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p>
<md-autocomplete ng-disabled="ctrl.isDisabled" md-no-cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-selected-item-change="ctrl.selectedItemChange(item)" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" placeholder="What is your favorite US state?">
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
<br/>
<md-checkbox ng-model="ctrl.simulateQuery">Simulate query for results?</md-checkbox>
<md-checkbox ng-model="ctrl.noCache">Disable caching of queries?</md-checkbox>
<md-checkbox ng-model="ctrl.isDisabled">Disable the input?</md-checkbox>
<p>By default, <code>md-autocomplete</code> will cache results when performing a query. After the initial call is performed, it will use the cached results to eliminate unnecessary server requests or lookup logic. This can be disabled above.</p>
</form>
</md-content>
please provide me the solution how to get the value of myString in the autocomplete directive select list
i had the same issue, this works for me:
function autoComplete(query) {
if (!query || query.length < 2) {
return vm.complete = [];
}
// http request
}

How to empty md-autocomplete text field after submit?

I used md-autocomplete inside html form, then I wanted to set its field to empty after submitting. I tried, as shown in the snippet, to use $setPristine() but it didn't work. I also tried to assign the model to null or empty string, but also it wasn't successful.
PS: Angularjs version I used is v1.3.15
angular.module("myApp", ["ngMaterial"])
.controller("main", function($scope){
$scope.searchString = "";
$scope.routeToSearchPage = function (searchString, form) {
$scope.form.$setPristine();
};
$scope.simulateQuery = false;
$scope.isDisabled = false;
$scope.states = loadAll();
$scope.querySearch = querySearch;
function querySearch (query) {
var results = query ? $scope.states.filter( createFilterFor(query) ) : $scope.states,
deferred;
if ($scope.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function loadAll() {
var allStates = "aaa, bbbb, cccc, bla";
return allStates.split(/, +/g).map( function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-aria.js"></script>
<script src="//rawgit.com/angular/bower-material/master/angular-material.js"></script>
<div ng-app="myApp">
<div ng-controller="main">
<form name="form"
ng-submit="submit(searchString);$event.preventDefault();">
<md-autocomplete
md-floating-label="search"
ng-disabled="isDisabled"
md-no-cache="noCache"
md-selected-item="selectedItem"
md-search-text="searchString"
md-items="item in querySearch(searchString)"
md-item-text="item.display"
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">
<md-item-template>
<span md-highlight-text="searchString" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
</md-autocomplete>
</form>
<md-button ng-click="routeToSearchPage(searchString, form)">
<md-icon class="material-icons">search</md-icon>
</md-button>
</div>
</div>
Here's an example of clearing an md-autocomplete - CodePen
Your snippet isn't actually showing the md-autocomplete as it should appear.
JS
$scope.clear = function () {
$scope.searchString = null;
};
I have also removed the markup below for the CodePen to work correctly:
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">

Is it possible to use Webix with AngularJs ui-router?

Only way I could get Webix to render subviews with ui-router was by using separate webix-ui directives but that does not seem right. Is there any clever way to make these two play nicely?
Yes its absolutely possible to use AngularJS UI routing with the Webix components. Here is the small example.
Script file consists of Wbix Component Code. It is mandatory for every Angular Webix Integration. It is present in the JavaScript file.
Angular UI routing has been done using the 'config' and all the Routes are mentioned inside the 'Template' section. You can replace this with the 'TemplateUrl' field and respective file names.
The Full example can be downloaded here from : https://github.com/TheAjinkya/AngularWebixApplication/tree/master/Angular_UI_Router_with_Webix_Tree
if (window.angular)
(function(){
function id_helper($element){
//we need uniq id as reference
var id = $element.attr("id");
if (!id){
id = webix.uid();
$element.attr("id", id);
}
return id;
}
function locate_view_id($element){
if (typeof $element.attr("webix-ui") != "undefined")
return $element.attr("id");
return locate_view_id($element.parent());
}
//creates webix ui components
angular.module("webix", [])
.directive('webixUi', [ "$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link:function ($scope, $element, $attrs, $controller){
var dataname = $attrs["webixUi"];
var callback = $attrs["webixReady"];
var watch = $attrs["webixWatch"];
var wxRoot = null;
var id = id_helper($element);
$element.ready(function(){
if (wxRoot) return;
if (callback)
callback = $parse(callback);
//destruct components
$element.bind('$destroy', function() {
if (wxRoot && !wxRoot.$destructed && wxRoot.destructor)
wxRoot.destructor();
});
//ensure that ui is destroyed on scope destruction
$scope.$on('$destroy', function(){
if (wxRoot && !wxRoot.$destructed && wxRoot.destructor)
wxRoot.destructor();
});
//webix-ui attribute has some value - will try to use it as configuration
if (dataname){
//configuration
var watcher = function(data){
if (wxRoot) wxRoot.destructor();
if ($scope[dataname]){
var config = webix.copy($scope[dataname]);
config.$scope =$scope;
$element[0].innerHTML = "";
wxRoot = webix.ui(config, $element[0]);
if (callback)
callback($scope, { root: wxRoot });
}
};
if (watch !== "false")
$scope.$watch(dataname, watcher);
watcher();
} else {
//if webix-ui is empty - init inner content as webix markup
if (!$attrs["view"])
$element.attr("view", "rows");
var ui = webix.markup;
var tmp_a = ui.attribute; ui.attribute = "";
//FIXME - memory leaking, need to detect the moment of dom element removing and destroy UI
if (typeof $attrs["webixRefresh"] != "undefined")
wxRoot = ui.init($element[0], $element[0], $scope);
else
wxRoot = ui.init($element[0], null, $scope);
ui.attribute = tmp_a;
if (callback)
callback($scope, { root: wxRoot });
}
//size of ui
$scope.$watch(function() {
return $element[0].offsetWidth + "." + $element[0].offsetHeight;
}, function() {
if (wxRoot) wxRoot.adjust();
});
});
}
};
}])
.directive('webixShow', [ "$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link:function ($scope, $element, $attrs, $controller){
var attr = $parse($attrs["webixShow"]);
var id = id_helper($element);
if (!attr($scope))
$element.attr("hidden", "true");
$scope.$watch($attrs["webixShow"], function(){
var view = webix.$$(id);
if (view){
if (attr($scope)){
webix.$$(id).show();
$element[0].removeAttribute("hidden");
} else
webix.$$(id).hide();
}
});
}
};
}])
.directive('webixEvent', [ "$parse", function($parse) {
var wrap_helper = function($scope, view, eventobj){
var ev = eventobj.split("=");
var action = $parse(ev[1]);
var name = ev[0].trim();
view.attachEvent(name, function(){
return action($scope, { id:arguments[0], details:arguments });
});
};
return {
restrict: 'A',
scope: false,
link:function ($scope, $element, $attrs, $controller){
var events = $attrs["webixEvent"].split(";");
var id = id_helper($element);
setTimeout(function(){
var first = $element[0].firstChild;
if (first && first.nodeType == 1)
id = first.getAttribute("view_id") || id;
var view = webix.$$(id);
for (var i = 0; i < events.length; i++) {
wrap_helper($scope, view, events[i]);
}
});
}
};
}])
.directive('webixElements', [ "$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link:function ($scope, $element, $attrs, $controller){
var data = $attrs["webixElements"];
var id = id_helper($element);
if ($scope.$watchCollection)
$scope.$watchCollection(data, function(collection){
setTimeout(function(){
var view = webix.$$(id);
if (view){
view.define("elements", collection);
view.refresh();
}
},1);
});
}
};
}])
.directive('webixData', [ "$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link:function ($scope, $element, $attrs, $controller){
var data = $attrs["webixData"];
var id = id_helper($element);
if ($scope.$watchCollection)
$scope.$watchCollection(data, function(collection){
if (collection){
setTimeout(function(){
loadData($element, id, collection, 0);
},1);
}
});
}
};
}]);
function loadData($element, id, collection, num){
if (num > 10) return;
var first = $element[0].firstChild;
if (first && first.nodeType == 1)
id = first.getAttribute("view_id") || id;
var view = webix.$$(id);
if (view){
if (view.options_setter){
view.define("options", collection);
view.refresh();
}else{
if (view.clearAll)
view.clearAll();
view.parse(collection);
}
} else {
webix.delay(loadData, this, [$element, id, collection], 100, num+1);
}
}
})();
<!doctype html>
<html lang="en" ng-app="webixApp">
<head>
<meta charset="utf-8">
<title>Webix - Angular : Layouts</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<script src="https://angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.webix.com/edge/webix.css">
<script type="text/javascript" src="https://cdn.webix.com/edge/webix.js"></script>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
var app = angular.module('webixApp', [ "webix", 'ui.router' ]);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/add");
$stateProvider
.state('/add', {
url : '/add',
template : 'This is the Routed Addition File'
})
.state('/sub', {
url : '/sub',
template : 'This is the Routed Subtraction File'
})
.state('/div', {
url : '/div',
template : 'This is the Routed Division File'
})
.state('/multi', {
url : '/multi',
template : 'This is the Routed Multiplication File'
})
})
app.controller('jsonCtrl', function($scope){
var treeData = { data: [
{id:"root", value:"Super Micro Flow", open:true, link : "add", data:[
{ id:"1", open:true, value:"AP1", link : "multi", data:[
{ id:"1.1", value:"2G09#M10000761", link : "div", data:[
{ id:"1.11", value:"2G09#M10000761", link : "add", data:[
{ id:"1.11", value:"2G09#M10000761", link : "sub" },
{ id:"1.12", value:"2G09#M10855757", link : "multi"},
{ id:"1.13", value:"2G09#D10PP0761", link : "div" }
] },
{ id:"1.12", value:"2G09#M10855757", link : "multi"},
{ id:"1.13", value:"2G09#D10PP0761", link : "div" }
] },
{ id:"1.2", value:"2G09#M10855757", link : "multi"},
{ id:"1.3", value:"2G09#D10PP0761", link : "div" }
]},
{ id:"2", open:false, value:"AP12", link : "multi",
data:[
{ id:"2.1", value:"2G09#M10000761", link : "sub" },
{ id:"2.2", value:"2G09#M10855757", link : "multi"},
{ id:"2.3", value:"2G09#D10PP0761", link : "div" }
]},
{ id:"3", open:false, value:"EP45", link : "div",
data:[
{ id:"3.1", value:"2G09#M10000761", link : "sub" },
{ id:"3.2", value:"2G09#M10855757", link : "multi"},
{ id:"3.3", value:"2G09#D10PP0761", link : "div" }
]},
{ id:"4", open:false, value:"CR7767", link : "sub",
data:[
{ id:"4.1", value:"2G09#M10000761", link : "sub" },
{ id:"4.2", value:"2G09#M10855757", link : "multi"},
{ id:"4.3", value:"2G09#D10PP0761", link : "div" }
]}
]}
]
}
$scope.myTree = {
view:"tree",
data: treeData,
template: "{common.icon()}{common.folder()}<a ui-sref='#link#' href='##link#'>#value#</a>",
}
})
</script>
</head>
<body ng-controller="jsonCtrl">
<div webix-ui type="space">
<div height="35">Welcome to Angular Webix App </div>
<div view="cols" type="wide" margin="10">
<div width="300">
<input type="text" placeholder="Type something here" ng-model="app">
Hello {{app}}!
<div webix-ui="myTree"></div>
</div>
<div view="resizer"></div>
<div view="tabview" >
<div header="Angular UI Routing Example">
<div ng-controller="jsonCtrl">
<div ui-view></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I do not know, I occupy BackboneJS, you can look at the example of Webix
var routes = new (Backbone.Router.extend({
routes:{
"":"index",
"menu/:id":"pagechange",
},
pagechange:function(id){
console.log("Change Page to "+ id);
$$("page"+id).show();
}
}));
routes.navigate("menu/"+1010101, { trigger:true });

Resting Model and collection on every click before fetch

Hi i have been working on app where onclick of the image you can add pin on the image anywhere and store its name and details. All work fine like i can add details and save it and it get saved into the database. But if you go back to another link and come back on the same. It shows the older stuff instead of the saved one in database.
I tried resetting and removing the model and collection but it doesnt work. Also tried destroying the model but it shows up errr as
Object function (){ return parent.apply(this, arguments); } has no method 'reset'
Below is my code :
/*MLP Backbone Starts Here*/
var MLPImage = Backbone.Model.extend({
});
var MLPImages = Backbone.Collection.extend({
model : MLPImage,
url: jQuery('#baseurl').val()+'index.php/api/example/scmlps/',
initialize : function(){
/*if(MLPImage.destroy()){
console.log("destroyed")
}else{
console.log("not destroyed")
}*/
this.deleteTask();
console.log(this)
this.on("reset", this.loadMLPImagesView,this);
this.on("pushpindata", this.pushpindetailsview,this);
this.on("error", this.errorMLPImageMessage,this);
this.on("mlperror", this.errorMLPpushpin,this);
console.log(this)
},
deleteTask: function() {
that = this;
this.model.reset();
this.model.destroy({
success: function() {
console.log(that.parent.collection);
}
});
return false;
},
loadMLPImagesView : function(){
// console.log(this);
//console.log(this.CollView.$el);
if(!this.CollView){
this.CollView = new MLPImagesView({collection:this})
}
this.CollView.render();
},
errorMLPImageMessage : function(){
jQuery('#imageBlocksDiv').html('<span id="noMsg"><h4>No images to display.</h4></span>');
},
pushpindetailsview : function(){
if(!this.pushpinview){
this.pushpinview = new pushpindetailsViews({collection:this})
}
this.pushpinview.render();
},
errorMLPImageMessage : function(){
jQuery('#clickable').append('<span id="noMsg"><h4>No images to display.</h4></span>');
}
});
var MLPImagesView = Backbone.View.extend({
el : jQuery('#imageBlocksDiv'),
events : {
'click .middle-box-title' : 'setsavevisisble',
'click .box-comment' : 'setsavevisisble',
'click .imagepopup' : 'mlppopupimage',
'click #closeme' : 'closepopup',
'click #closesave' : 'closepindetails',
'click #details' : 'savepushpindetails',
'click #closeupdate' : 'closeupdatepushpin',
'click .ui-draggable-mlp': 'passpushpindobjid',
'dragenter img.ui-draggable-mlp' : 'alertMe',
},
alertMe: function (e) {
jQuery(e.currentTarget).draggable({ containment: "parent" });
jQuery(e.currentTarget).mouseup(function(){
var x = jQuery(this).css("left");
var x_myarr = x.split("px");
var x_val = x_myarr[0];
var y = jQuery(this).css("top");
var y_myarr = y.split("px");
var y_val = y_myarr[0];
//console.log(jQuery(this).attr('data-objectid'))
objid = jQuery(this).attr('data-objectid');
var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'x_val' : x_val,
'y_val' : y_val,
'id' : objid
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
//console.log(response)
}
});
});
},
setsavevisisble : function(ev){
jQuery(jQuery(ev.currentTarget).parents().eq(1).find('#saveGallery')).css('display','block');
},
closepindetails : function(){
jQuery('.close').show();
jQuery('#title').val('');
jQuery('#description').val('');
jQuery('.pinDetails').hide();
jQuery('.popupmlp').find('.ui-draggable-mlp').last().remove();
},
closeupdatepushpin : function(){
jQuery('.close').show();
jQuery('.updatepin').hide();
},
passpushpindobjid : function(ev){
var that = this;
var leftval = jQuery(ev.currentTarget).css('left');
var topval = jQuery(ev.currentTarget).css('top');
jQuery(ev.currentTarget).parents().eq(0).append("<img id='pushpin_loader' style='position:absolute;left:"+leftval+";top:"+topval+";' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />");
jQuery('.updatepin').remove();
jQuery('#updatetitle').val('');
jQuery('#updatedescription').html('');
var img_id = jQuery(ev.currentTarget).attr('data-objectid'); //console.log(img_id)
that.retrivepushpindetails(img_id);
},
savepushpindetails : function(ev){
var popup_id = jQuery('.pinDetails').attr('data-popupid');
jQuery('#popup'+popup_id).find('#btn').html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />");
var x = jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').css("left");
var x_myarr = x.split("px");
var x_val = x_myarr[0];
var y = jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').css("top");
var y_myarr = y.split("px");
var y_val = y_myarr[0];
var inputData = {
'description': jQuery('#description').val(),
'title': jQuery('#title').val(),
'imageid' : jQuery('#hideobjid').val(),
'projectId' : jQuery('#ugallerymlp').val(),
'total_img_des' : jQuery('#clickable').html(),
'pushpin_number' : popup_id,
'x_val' : x_val,
'y_val' : y_val,
'canvas_height' : jQuery('#clickable').height(),
'canvas_width' : jQuery('#clickable').width()
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').attr('data-objectid',response.objectId);
/*var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'id' : response.objectId
};
jQuery.ajax({
'type':'POST',
'url': 'http://www.dwellar.com/portal/index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
}
});*/
alert("Saved");
jQuery('#popup'+popup_id).find('#btn').html('<input type="button" name="details" value="Save Detail" id="details">');
jQuery('#title').val('');
jQuery('#description').val('');
jQuery('.pinDetails').hide();
jQuery('.close').show();
}
});
},
mlppopupimage : function(ev){
var that = this;
jQuery("#clickable").html('');
jQuery('#mlpimagepopup').remove();
jQuery('#imageBlocksDiv').append('<div id="mlpimagepopup"></div>');
jQuery('#mlpimagepopup').append('<div class="pinDetails"><div id="closesave"><img src="http://www.dwellar.com/portal/assets/images/closenew.png"></div><table style="float:left; width:100%;"><tbody><tr><td style="height: 40px;"><span>Title :</span></td><td><span><input type="text" name="title" id="title" class="title" style="width: 162;"></span></td></tr><tr><td style="padding-top: 6%;height: 40px;"><span style="vertical-align: top;">Description :</span></td><td><span><textarea name="description" id="description" class="description" style="width: 98%;"></textarea></span></td></tr><tr><td id="btn" colspan="3"><input type="button" name="details" value="Save Detail" id="details"></td></tr></tbody></table></div>');
var hidval = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id');
var imgurl = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src'); //console.log(imgurl)
jQuery.ajax({
'type':'GET',
'url': jQuery('#baseurl').val()+'index.php/api/authentication/randomdata/scpushpin_details/imageid/'+hidval,
success : function(response){
//console.log(response.length)
for(var i = 0; i<response.length; i++){
jQuery('#clickable').append('<img src="http://www.elementalcrafts.com/dwellarportal/images/location.png" style="position:absolute;height:35px;width:22px;left:'+response[i].x_val+';top:'+response[i].y_val+'" data-objectid="'+response[i].objectId+'" class="ui-draggable-mlp" title="'+response[i].title+'"data-uniqueid ="'+response[i].pushpin_number+'">');
}
}
});
jQuery('#mask').show();
jQuery('#mlpimagepopup').show();
jQuery('#mlpimagepopup').append('<input type="hidden" value="'+hidval+'" id="hideobjid"><div class="close" id="closeme" style="margin: -14px -8px 0px 0px;font-size: 30px;"><img src="http://www.dwellar.com/portal/assets/images/closenew.png"></div><div style="margin:7px;" class="popupmlp" id="clickable"><img src="'+imgurl+'"></div>');
//jQuery('#clickable').append('<div></div>');
jQuery('.popupmlp').bind('click', function (ev) {
jQuery('.close').hide();
jQuery('.ui-draggable-mlp').each(function(){
var pinval = jQuery(this).attr('data-objectid');
if(typeof pinval == 'undefined'){
var pi = jQuery(this).attr('data-uniqueid');
jQuery('img[data-uniqueid="'+pi+'"]').remove();
}
});
var divId = document.getElementById("clickable");
var divChild = jQuery('.popupmlp img').length;
var currentElemId= divChild+1;
var jQuerydiv = jQuery(ev.target);
var offset = jQuerydiv.offset();
var x = ev.clientX - offset.left ; //console.log(x)
var y = ev.clientY - offset.top ;
var xfloor = Math.floor(x);
var yfloor = Math.floor(y);
var scrollval = jQuery('.scrollval').last().attr('value'); //console.log(scrollval)
if(scrollval){}
else{
var scrollval = "0";
}
var nsv = Number(+yfloor + +scrollval); //console.log(nsv);
var pinImgElement= jQuery('<img class="ui-draggable-mlp">'); //console.log(pinImgElement);
pinImgElement.appendTo(jQuery(this));
pinImgElement.css({left:xfloor,top:nsv-25,'position':'absolute','width':'22px'}).attr('src','http://www.elementalcrafts.com/dwellarportal/images/location.png');
//pinImgElement.booklet( {keyboard: true} );
pinImgElement.draggable({ containment: "parent"});
pinImgElement.attr('data-uniqueid',currentElemId);
jQuery('.pinDetails').show();
jQuery('.pinDetails').attr('id','popup'+currentElemId);
jQuery('.pinDetails').attr('data-popupid',currentElemId);
jQuery('.updatepin').remove();
jQuery('#title').focus();
pinImgElement.on('click',function(){
var img_id = jQuery(this).attr('data-objectid');
that.retrivepushpindetails(img_id);
});
});
},
retrivepushpindetails : function(img_id){
jQuery('.pinDetails').hide();
jQuery('.ui-draggable-mlp').each(function(){
var pinval = jQuery(this).attr('data-objectid'); //console.log(pinval)
if(typeof pinval === 'undefined'){
var pi = jQuery(this).attr('data-uniqueid');
jQuery('img[data-uniqueid="'+pi+'"]').remove();
}
});
var that = this;
this.collection.fetch({data: jQuery.param({'objectid':img_id}), success:function(resp){
// console.log(resp)
that.collection.trigger("pushpindata");
},
error : function(){
//that.collection.trigger("mlperror");
}
});
},
closepopup : function(){
jQuery('#mask').fadeOut(100);
jQuery('#mlpimagepopup').fadeOut(500);
new pushpindetailsViews().cleanup();
},
initialize : function(){
var that = this;
jQuery('#ugallerymlp').change(function(){
that.filterByProjectsMLPImage(jQuery('#ugallerymlp').val());
});
},
render : function(){
this.iterateMsg();
},
iterateMsg : function(){
var that = this;
jQuery('#imageBlocksDiv').html('');
_.each(this.collection.models, function (msg) {
that.renderMsg(msg)
//console.log(msg)
});
pinterest();
},
renderMsg : function(msg){
var mV = new MLPImageView({
model : msg
});
this.$el.append(mV.render().el);
},
filterByProjectsMLPImage : function(projectId){//alert('thius');
var that = this;
var projectId = jQuery('#ugallerymlp').val();
//console.log(projectId,this.collection)
this.collection.fetch({data: jQuery.param({'projectId': projectId}), success:function(resp){
//console.log(resp)
that.collection.trigger("reset");
},
error : function(){
that.collection.trigger("error");
}
});
},
cleanup: function() {
//this.undelegateEvents();
$(this.el).find('#mlpimagepopup').empty();
//jQuery(this.el).find('#mlpimagepopup').empty();
}
});
var pushpindetailsViews = Backbone.View.extend({
el : jQuery('#mlppushpindetails'),
render : function(){
var that = this;
_.each(this.collection.models, function (pusmsg) {
that.pushpinMsg(pusmsg);
//console.log(pusmsg)
});
},
pushpinMsg : function(pusmsg){
var pmV = new mlppushpindetails({
model : pusmsg
});
this.$el.append(pmV.render().el);
},
cleanup: function() {
this.undelegateEvents();
$(this.el).empty();
}
});
var mlppushpindetails = Backbone.View.extend({
template : jQuery('#pushpindetails').html(),
events : {
'click #updatepushpin': 'passpushpindtails',
'click #deletepushpin': 'passpushpindtails',
'click #closeupdate' : 'closeupdatepopup',
},
render : function(){
//jQuery('#pushpinmlpdetails').html('');
jQuery('#pushpin_loader').remove();
_.bindAll(this,'updatepushpindetails')
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
//console.log(this.el);
return this;
},
closeupdatepopup: function(){
jQuery('.close').show();
jQuery('.updatepin').parents().eq(0).remove();
jQuery('.updatetitle').val('');
jQuery('.updatedescription').html('');
},
passpushpindtails:function(ev){
var selectedButton = jQuery(ev.currentTarget).attr('id');
var title= jQuery('.updatetitle').val();
var description = jQuery('.updatedescription').val();
var objId = jQuery('#hideval').val();
//console.log(selectedButton,objId)
selectedButton == 'updatepushpin' ? this.updatepushpindetails(objId,title,description): this.deletepushpindetails(objId);
//jQuery(jQuery(ev.currentTarget).parents().eq(1).find('#saveGallery')).css('display','none');
//jQuery('#updatepin').html("<img style='float:right;margin:5px 15px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
return false;
},
updatepushpindetails : function(objId,title,description){
jQuery('#updatepushpin').parents().eq(0).html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
var inputData = {
'title': title,
'description': description,
'id' : objId
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
alert('updated');
jQuery('.close').show();
jQuery('#updatetitle').html('');
jQuery('#updatedescription').html('');
jQuery('.updatepin').parents().eq(0).remove();
jQuery('#updatepushpin').parents().eq(0).html('<input type="button" name="Update" id="updatepushpin" class="updatepushpin" value="Update">')
}
});
},
deletepushpindetails : function(objId){
var r=confirm("Want to delete!")
if (r==true)
{
jQuery('#deletepushpin').parents().eq(0).html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
if(typeof objId!='undefined'){
var inputData = {
'id' : objId
}
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpin/',
'data' : inputData,
success : function(response){
alert("Delete Pushpin")
//console.log(jQuery('#clickable').html(),jQuery('#currentimageid').val())
/*var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'id' : jQuery('#currentobjid').val()
};
jQuery.ajax({
'type':'POST',
'url': 'http://www.dwellar.com/portal/index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
console.log(response)
}
});*/
jQuery('.updatepin').parents().eq(0).remove();
jQuery('.updatetitle').html('');
jQuery('.updatedescription').html('');
jQuery('.popupmlp img[data-objectid="'+objId+'"]').last().remove()
jQuery('.close').show();
jQuery('#deletepushpin').parents().eq(0).html('<input type="button" name="Delete" id="deletepushpin" class="deletepushpin" value="Delete">')
}
});
}
}
}
});
var MLPImageView = Backbone.View.extend({
className : "block",
initialize: function(){
var that = this;
jQuery('.inner-middle').mouseover(function(ev) {
jQuery(this).find('.editbutton').show();
}).mouseout(function(ev) {
jQuery(this).find('.editbutton').hide();
});
jQuery('.closedialog').click(function(){
jQuery('#dialog').fadeOut(1000);
});
},
template : jQuery('#mlpimagesBlock').html(),
events : {
'click #saveGallery': 'passImageDetails',
'click #deleteGallery': 'passImageDetails',
'click #sethome' : 'setashome',
'click .editbutton' : 'enableediting',
'click .box-comment' : 'enableediting',
'click .middle-box-title' : 'enableediting',
'click #cancelgallery' : 'cancelgallery',
},
enableediting : function(ev){
new galleryimageuploader(jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id'))
var selectedButton = jQuery(ev.currentTarget).attr('class'); //console.log(selectedButton)
jQuery(ev.currentTarget).append('<input type="hidden" id="oldtitleval" value="'+jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text()+'"><input type="hidden" id="olddescriptoinval" value="'+jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text()+'"><input type="hidden" id="oldimagesrc" value="'+jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src')+'">');
jQuery('.editbutton').hide();
jQuery('.editbutton').attr('class','ch-inner');
jQuery('.box-comment').prop("contentEditable", false);
jQuery('.middle-box-title').prop("contentEditable", false);
jQuery('.box-comment').attr('class','changebox');
jQuery('.middle-box-title').attr('class','changetitle');
jQuery('.imagepopup').attr('class','changeimgstyle');
if(selectedButton == "box-comment" || selectedButton == "galleryimgstyle"){
jQuery(ev.currentTarget).parents().eq(2).find('.editbutton').hide();
jQuery(ev.currentTarget).parents().eq(2).find('.metadata').css('visibility','visible');
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').css('z-index','9999');
jQuery(ev.currentTarget).parents().eq(2).find('.changetitle').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(2).find('.changetitle').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(2).find('.changeimgstyle').css("opacity", "0.4");
jQuery(ev.currentTarget).parents().eq(2).find('.gallerybox').show();
}
else{
jQuery(ev.currentTarget).parents().eq(1).find('.metadata').css('visibility','visible');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').css('z-index','9999');
jQuery(ev.currentTarget).parents().eq(1).find('.changetitle').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(1).find('.changetitle').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(1).find('.changeimgstyle').css("opacity", "0.3");
jQuery(ev.currentTarget).parents().eq(1).find('.gallerybox').show();
}
return false;
},
render : function(){
_.bindAll(this,'saveImageDetails')
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
},
passImageDetails:function(ev){
var selectedButton = jQuery(ev.currentTarget).attr('id');
var imgTitle= jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text(); //console.log(imgTitle)
var imgDescription = jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text();
var imageUrl = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src');
var spl = imageUrl.substring(imageUrl.lastIndexOf('/')).split('/'); //console.log(spl[1])
var objId = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id');
//console.log(selectedButton,objId,imgTitle,imgDescription)
selectedButton == 'saveGallery' ? this.saveImageDetails(objId,imgTitle,imgDescription,imageUrl,ev): this.deleteImage(objId,spl[1],ev);
jQuery(jQuery(ev.currentTarget).parents().eq(1).find('.metadata')).html("<img style='float:right' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />").css('height','28px');
return false;
},
saveImageDetails : function(objId,imgTitle,imgDescription,imageUrl,sethomeid){
var inputData = {
'name': imgTitle,
'description': imgDescription,
'image_url' : imageUrl,
'projectId' : jQuery('#ugallerymlp').val()
};
inputData.id = (objId != null) ? objId:"";
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlps/',
'data' : inputData,
success : function(response){
if(typeof response.objectId!='undefined'){
jQuery('.block').find("img[src='"+inputData.image_url+"']").attr('id',response.objectId);
jQuery('#'+response.objectId).parents().eq(2).find('div[id="tmploader"]').hide();
jQuery('#'+response.objectId).parents().eq(2).find('div[id="displaysus"]').attr('id',response.objectId);
}
jQuery('#'+response.objectId).parents().eq(2).find('.metadata').css({'visibility':'hidden','height':'28px'});
if(sethomeid == "abc"){
//jQuery('#dialog').show();
jQuery('#'+response.objectId).parents().eq(2).find('div[id="'+response.objectId+'"]').show()
jQuery('#'+response.objectId).parents().eq(2).find('div[id="'+response.objectId+'"]').fadeOut(3000);
}
else{
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
}
if(objId){jQuery('.metadata').css({'visibility':'hidden','height':'28px'});}
jQuery('#'+objId+'abc').show();
jQuery('#'+objId+'abc').fadeOut(3000);
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css('opacity', '1');
jQuery('.gallerybox').hide();
}
});
},
deleteImage : function(objId,imageUrl,sethomeid){
//console.log(objId)
var r=confirm("Want to delete!")
if (r==true)
{
if(typeof objId!='undefined'){
var inputData = {
'id' : objId,
'imgurl' : imageUrl
}
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlp/',
'data' : inputData,
success : function(response){
if(objId){jQuery('.metadata').css({'visibility':'hidden','height':'28px'});}
jQuery('#'+objId).parents().eq(3).remove();
pinterest(undefined);
if(sethomeid == "abc"){
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
pinterest(undefined);
}
else{
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
}
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpdetails/',
'data' : inputData,
success : function(resdata){ console.log(resdata)}
});
}
});
}
}
else{
jQuery('.metadata').css({'visibility':'hidden','height':'28px'});
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
}
},
cancelgallery : function(ev){
jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text(jQuery('#oldtitleval').val());
jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text(jQuery('#olddescriptoinval').val());
jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src',jQuery('#oldimagesrc').val());
jQuery('.metadata').css({'visibility':'hidden','height':'28px'});
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
}
});
/MLP Backbone Ends Here/
Can anyone help me with the destroying and clearing the collection and model. Any help is deeply appreciated.
Thanking you,
Santosh Upadhayay
My first reaction would be to confirm that you don't have 2 of the same view on the page. I suspect that your original view still exists when you navigate back to the page. So it's this view that's being shown before your updated view which makes you think it's not being updated. So confirm that the html you expect to see isn't showing up in the wrong place.
If, on the other hand, you never see the correct html (even after the first interaction), then I suspect it has to do with your rendering logic. The model may be correctly syncing with the server, but you're not listening to the correct events from the view; or perhaps you are listening to the model event, but your handler is NOT rendering the view again.

Resources