ember.js <select> populated and selected by two different objects - javascript

I'm new to ember, so maybe I'm doing this wrong.
I'm trying to create a select dropdown, populated with three values supplied from an external datasource. I'd also like to have the correct value in the list selected based on the value stored in a different model.
Most of the examples I've seen deal with a staticly defined dropdown. So far what I have is:
{{#view contentBinding="App.formValues.propertyType" valueBinding="App.property.content.propertyType" tagName="select"}}
{{#each content}}
<option {{bindAttr value="value"}}>{{label}}</option>
{{/each}}
{{/view}}
And in my module:
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [
Ember.Object.create({"label":"App","value":"app", "selected": true}),
Ember.Object.create({"label":"Website","value":"website", "selected": false}),
Ember.Object.create({"label":"Mobile","value":"mobile", "selected": false})
]
});
And finally my object:
App.Property = Ember.Object.extend({
propertyType: "app"
});
App.property = Ember.Object.create({
content: App.Property.create(),
load: function(id) {
...here be AJAX
}
});
The dropdown will populate, but it's selected state won't reflect value of the App.property. I know I'm missing some pieces, and I need someone to just tell me what direction I should go in.

The answer was in using .observes() on the formValues. For some reason .property() would toss an error but .observes() wouldn't.
I've posted the full AJAX solution here for reference and will update it with any further developments.
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [],
load: function() {
var that = this;
$.ajax({
url: "/api/form/propertytype",
dataType: "json",
success: function(data) {
that.set("content", []);
_.each(data, function(item) {
var optionValue = Ember.Object.create(item);
optionValue.set("selected", false);
that.pushObject(optionValue);
});
that.update();
}
});
},
update: function() {
var content = this.get("content");
content.forEach(function(item) {
item.set("selected", (item.get("value") == App.property.content.propertyType));
});
}.observes("App.property.content.propertyType")
});
App.formValues.propertyType.load();

Related

How do i pass a received array into underscore template

I am getting a long array from PHP containing various data objects.
[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}]
My Backbone View which will be rendering the data is
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(html) {
console.log(html);
var compiledTemplate = _.template($('#content-box').html(), html);
_this.$el.html(compiledTemplate);
},
error: function(e) {
console.log(e);
}
});
return false;
}
});
My workHTML which will be rendered by Underscore is
<script type="text/template" id="content-box">
<div class="workhead">
<h3 class="msg comment"><%= comment%></h3>
<p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>
How do I implement a underscore loop here?
You should take advantage of Backbone's features. And to do that, you need to understand how to use a REST API with Backbone.
Backbone's Model is made to manage a single object and handle the communication with the API (GET, POST, PATCH, PUT requests).
Backbone's Collection role is to handle an array of model, it handles fetching it (GET request that should return a JSON array of objects) and it also parse each object into a Backbone Model by default.
Instead of hard-coding a jQuery ajax call, use a Backbone collection.
var WorkCollection = Backbone.Collection.extend({
url: "includes/server_api.php/work",
});
Then, modularize your views. Make an item view for each object of the array you received.
var WorkItem = Backbone.View.extend({
// only compile the template once
template: _.template($('#content-box').html()),
render: function() {
// this is how you pass data to the template
this.$el.html(this.template(this.model.toJSON()));
return this; // always return this in the render function
}
});
Then your list view looks like this:
var WorkPage = Backbone.View.extend({
initialize: function(options) {
this.itemViews = [];
this.collection = new WorkCollection();
this.listenTo(this.collection, 'reset', this.render);
// this will make a GET request to
// includes/server_api.php/work
// expecting a JSON encoded array of objects
this.collection.fetch({ reset: true });
},
render: function() {
this.$el.empty();
this.removeItems();
this.collection.each(this.renderItem, this);
return this;
},
renderItem: function(model) {
var view = new WorkItem({
model: model
});
this.itemViews.push(view);
this.$el.append(view.render().el);
},
// cleanup to avoid memory leaks
removeItems: function() {
_.invoke(this.itemViews, 'remove');
this.itemViews = [];
}
});
It's unusual to set the url in the render function, you should keep the responsibilities scoped to the right place.
The router could be something like:
var Router = Backbone.Router.extend({
routes: {
'work': 'workPage'
},
workPage: function() {
var page = new WorkPage({
el: $('#indexcontent'),
});
}
});
Then, if you want to see the work page:
var myRouter = new Router();
Backbone.history.start();
myRouter.navigate('#work', { trigger: true });
Templates and RequireJS
My index.html page contains this
indexcontent div but the content-box which contains the template
format which we are compiling is stored in different work.html. So,
if i dont load this work.html in my main index.html i am unable to
access content-box.
I would recommend to use the text require.js plugin and load each template for the view like this:
The work-item.js file:
define([
'underscore', 'backbone',
'text!templates/work-item.html',
], function(_, Backbone, WorkItemTemplate) {
var WorkItem = Backbone.View.extend({
template: _.template(WorkItemTemplate),
/* ...snip... */
});
return WorkItem;
});
The work-page.js file:
define([
'underscore', 'backbone',
'text!templates/work-page.html',
], function(_, Backbone, WorkPageTemplate) {
var WorkPage = Backbone.View.extend({
template: _.template(WorkPageTemplate),
});
return WorkPage;
});
In your index.html file you need to have _.each() method to iterate throught each element
<% _.each(obj, function(elem){ %>
<div class="workhead">
<h3 class="msg comment"><%= elem.comment %></h3>
<p class="date"><%= elem.date%></p>
</div>
<% }) %>
I make variable of your response just to have data to work with. In your View you need to set point on template
template: _.template($("#content-box").html()), and in render method just send data as object.
Here is working code : jsFiddle
Here is one way to load the template for each value in the data array.
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(data) {
console.log(data);
var $div = $('<div></div>');
_.each(data, function(val) {
$div.append(_.template($('#content-box').html(), val));
});
_this.$el.html($div.html());
},
error: function(e) {
console.log(e);
}
});
return false;
}
});

knockout subscription not working

I have been trying to subscribe to when a dropdown value changes. I have the following logic however I cannot seem to get it working.
HTML
<div id="case-pin-#modelItem.CaseID" data-caseid="#modelItem.CaseID" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
JS
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function (newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
}
var pinObjs = [];
$(function () {
pinObjs = [];
$(".pinBinding").each(function () {
var caseId = this.getAttribute("data-caseid");
var view = new UserPinViewModel(caseId);
pinObjs.push(view);
ko.cleanNode(this);
ko.applyBindings(view, this);
});
})
The userPins array is populated by an AJAX call to the server as the values in the dropdown are dependent upon another section of the website which can change the values in the dropdown - here the logic I have used to populate the array.
function getPins() {
$.ajax({
type: 'POST',
url: '/Home/GetPins',
success: function (data) {
for (var i = 0; i < pinObjs.length; i++) {
pinObjs[i].userPins(data);
}
},
error: function (request, status, error) {
alert("Oooopppppsss! Something went wrong - " + error);
}
});
}
The actual values in the dropdowns all change to match what is returned from the server however whenever I manually change the dropdown, the subscription event is not fired.
You're using both jQuery and Knockout to manipulate the DOM, which is not a good idea. The whole idea of Knockout is that you don't manipulate the DOM, it does. You manipulate your viewModel.
Using cleanNode is also a code smell, indicating that you're doing things the wrong way. Knockout will handle that if you use the tools Knockout provides.
In this case, I was going to suggest a custom binding handler, but it looks like all you really want is to have a UserPinViewModel object created and applied to each instance of your .pinBinding element in the HTML. You can do that using the with binding, if you expose the UserPinViewModel constructor in your viewModel.
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function(newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
// Pretend Ajax call to set pins
setTimeout(() => {
self.userPins([{
Name: 'option1',
Id: 1
}, {
Name: 'option2',
Id: 2
}, {
Name: 'option3',
Id: 3
}])
}, 800);
// Later, the options change
setTimeout(() => {
self.userPins([{
Name: 'animal1',
Id: 'Elephant'
}, {
Name: 'animal2',
Id: 'Pony'
}, {
Name: 'animal3',
Id: 'Donkey'
}])
}, 4000);
}
ko.bindingHandlers.pin = {
init: () => null,
update: () => null
};
ko.applyBindings({
pinVm: UserPinViewModel
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="case-pin-#modelItem.CaseID" data-bind="with: new pinVm('someCaseId')" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
Your getPins function suggests that the .pinBinding elements should correspond to the data being received. In that case, pinObjs should really be a part of your viewModel, and the elements should be generated (perhaps in a foreach) from the data, rather than being hard-coded. I don't know how that works with what I presume is the server-side #modelItem.CaseID, though.

Selectize: Setting Default Value in onInitialize with setValue

I have a web application with multiple Selectize objects initialized on the page. I'm trying to have each instance load a default value based on the query string when the page loads, where ?<obj.name>=<KeywordID>. All URL parameters have already been serialized are are a dictionary call that.urlParams.
I know there are other ways to initializing Selectize with a default value I could try; but, I'm curious why calling setValue inside onInitialize isn't working for me because I'm getting any error messages when I run this code.
I'm bundling all this JavaScript with Browserify, but I don't think that's contributing to this problem.
In terms of debugging, I've tried logging this to the console inside onInititalize and found that setValue is up one level in the Function.prototype property, the options property is full of data from load, the key for those objects inside options corresponds to the KeywordID. But when I log getValue(val) to the console, I get an empty string. Is there a way to make this work or am I ignoring something about Selectize or JavaScript?
module.exports = function() {
var that = this;
...
this.selectize = $(this).container.selectize({
valueField: 'KeywordID', // an integer value
create: false,
labelField: 'Name',
searchField: 'Name',
preload: true,
allowEmptyOptions: true,
closeAfterSelect: true,
maxItems: 1,
render: {
option: function(item) {
return that.template(item);
},
},
onInitialize: function() {
var val = parseInt(that.urlParams[that.name], 10); // e.g. 5
this.setValue(val);
},
load: function(query, callback) {
$.ajax({
url: that.url,
type: 'GET',
error: callback,
success: callback
})
}
});
};
...
After sprinkling in some console.logs into Selectize.js, I found that the ajax data hadn't been imported, when the initialize event was triggered. I ended up finding a solution using jQuery.when() to make setValue fire after the data had been loaded, but I still wish I could find a one-function-does-one-thing solution.
module.exports = function() {
var that = this;
...
this.selectize = $(this).container.selectize({
valueField: 'KeywordID', // an integer value
create: false,
labelField: 'Name',
searchField: 'Name',
preload: true,
allowEmptyOptions: true,
closeAfterSelect: true,
maxItems: 1,
render: {
option: function(item) {
return that.template(item);
},
},
load: function(query, callback) {
var self = this;
$.when( $.ajax({
url: that.url,
type: 'GET',
error: callback,
success: callback
}) ).then(function() {
var val = parseInt(that.urlParams[that.name], 10); // e.g. 5
self.setValue(val);
});
}
});
};
...
You just need to add the option before setting it as the value, as this line in addItem will be checking for it:
if (!self.options.hasOwnProperty(value)) return;
inside onInitialize you would do:
var val = that.urlParams[that.name]; //It might work with parseInt, I haven't used integers in selectize options though, only strings.
var opt = {id:val, text:val};
self.addOption(opt);
self.setValue(opt.id);
Instead of using onInitialize you could add a load trigger to the selectize. This will fire after the load has finished and will execute setValue() as expected.
var $select = $(this).container.selectize({
// ...
load: function(query, callback) {
// ...
}
});
var selectize = $select[0].selectize;
selectize.on('load', function(options) {
// ...
selectize.setValue(val);
});
Note that for this you first have to get the selectize instanze ($select[0].selectize).
in my case it need refresh i just added another command beside it
$select[0].selectize.setValue(opt);
i added this
$select[0].selectize.options[opt].selected = true;
and changes applied
but i dont know why?
You can initialize each selectize' selected value by setting the items property. Fetch the value from your querystring then add it as an item of the items property value:
const selectedValue = getQueryStringValue('name') //set your query string value here
$('#sel').selectize({
valueField: 'id',
labelField: 'title',
preload: true,
options: [
{ id: 0, title: 'Item 1' },
{ id: 1, title: 'Item 2' },
],
items: [ selectedValue ],
});
Since it accepts array, you can set multiple selected items

Set jsTree Node to "Undetermined" State

I'm using jsTree to show a tree with checkboxes. Each level of nodes is loaded on-demand using the json_data plugin.
If a node's descendent is checked, then that node should be in an "undetermined state" (like ACME and USA).
The problem is, the tree starts out collapsed. ACME looks unchecked but should be undetermined. When I finally expand to a checked node, jsTree realizes the ancestors should be undetermined.
So I need to be able to put a checkbox in the undetermined state without loading its children.
With jsTree you can pre-check a box by adding the jstree-checked class to the <li>. I tried adding the jstree-undetermined class, but it doesn't work. It just puts them in a checked state.
Here's my code:
$("#tree").jstree({
plugins: ["json_data", "checkbox"],
json_data: {
ajax: {
url: '/api/group/node',
success: function (groups) {
var nodes = [];
for (var i=0; i<groups.length; i++) {
var group = groups[i];
var cssClass = "";
if(group.isSelected)
cssClass = "jstree-checked";
else if(group.isDecendantSelected)
cssClass = "jstree-undetermined";
nodes.push({
data: group.name,
attr: { 'class': cssClass }
});
}
return nodes;
}
}
}
})
My Question
How do I set a node to the undetermined state?
I had the same problem and the solution I found was this one:
var tree = $("#tree").jstree({
plugins: ["json_data", "checkbox"],
json_data: {
ajax: {
url: '/api/group/node',
success: function(groups) {
var nodes = [];
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var checkedState = "false";
if (group.isSelected)
checkedState = "true";
else if (group.isDecendantSelected)
checkedState = "undetermined";
nodes.push({
data: group.name,
attr: { 'checkedNode': checkedState }
});
}
return nodes;
},
complete: function () {
$('li[checkedNode="undetermined"]', tree).each(function () {
$(this).removeClass('jstree-unchecked').removeClass('jstree-checked').addClass('jstree-undetermined');
});
$('li[checkedNode="true"]', tree).each(function () {
$(this).removeClass('jstree-unchecked').removeClass('jstree-undetermined').addClass('jstree-checked');
});
$('li[checkedNode="false"]', tree).each(function () {
$(this).removeClass('jstree-checked').removeClass('jstree-undetermined').addClass('jstree-unchecked');
});
}
}
}
});
Hope it helps you!
Maybe this changed in the meanwhile...
But now (version 3.0.0) the really simple solution works:
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
undetermined : boolean // is the node undetermined <<==== HERE: JUST SET THIS
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
Learned directly from the source code at: https://github.com/vakata/jstree/blob/6507d5d71272bc754eb1d198e4a0317725d771af/src/jstree.checkbox.js#L318
Thank you guys, and I found an additional trick which makes life a little better, but it requires a code change in jstree.js. Looks like an oversight:
Look at the get_undetermined function, and scan for the keyword break. That break should be a continue.
If you make that one change, then all you need to do is provide the state (for the main object and its children), and jstree will automatically take care of cascading upwards for undetermined state. It was bailing out early from the scripting and failing to catch all the undetermined nodes properly, requiring the above ugly workarounds for styling and such.
Here's my config (no special attrs or complete() function required) using AJAX:
var tree = $('#jstree').jstree({
"core": {
"themes": {
"variant": "large"
},
'data': {
'url': function (node) {
return "{{API}}/" + node.id + "?product_id={{Product.ID}}"
},
'dataType': 'json',
'type': 'GET',
'success': function (data) {
if (data.length == 0) {
data = rootStub
}
return {
'id': data.id,
'text': data.text,
'children': data.children,
'state': data.state,
}
}
}
},
"checkbox": {
// "keep_selected_style": false,
"three_state": false,
"cascade": "undetermined"
},
"plugins": ["wholerow", "checkbox"],
});

Unable to output from JSON file - Backbone

Trying to fetch JSON data when the div is clicked, but not able to see the output. I am using Backbone Collection to pull json data. Tried to output json data to console and also within another div. The content from json file is also listed below.
<div class = "test">Click </div>
<div class = "new_test"> </div>
JS
var myModel = Backbone.Model.extend();
var myCollection = Backbone.Collection.extend({
model: myModel,
url : "myjson.json"
})
var jobs = new myCollection();
var myView = Backbone.View.extend({
el : 'div',
events : {
'click div.test' : 'render'
},
initialize : function(){
jobs.fetch();
},
render : function(){
jobs.each(function(myModel){
var _comp = myModel.get('company');
$('div.new_test').html(_comp);
console.log(_comp)
})
}
})
Json File :
[
{
"company": "Ford",
"Type": "Automobile"
},
{
"company": "Nike",
"Type": "Sports"
}
]
You have to call the render function of your view to see the results. You cannot instantiate a collection object and expect to see results.
Code hasn't been tested.
var myView = Backbone.View.extend({
el : 'div',
events : {
'click div.test' : 'render'
},
initialize : function(){
jobs.fetch();
this.render();
},
render : function(){
jobs.each(function(myModel){
var _comp = myModel.get('company');
$('div.new_test').html(_comp);
console.log(_comp)
})
}
})
var yourView = new myView();
I have the same problem a few weeks ago.
Check path for Your JSON.
For example when You have structure of directories like this:
-js
- collection
collection.js
- json
myjson.json
Backbone collection You set like this:
url: 'js/json/event.json',
Check in Firefox, in Chrome we have a Cross-browser thinking
and check this:
jobs.fetch({
reset: true,
success: function (model, attributes) {
//check here if json is loaded
}
});

Categories