I will just show the part of the code I am having problens. If you think that you need to see all the code, let me know.
My Controller:
index: function() {
var documents = new App.Collections.Documents();
documents.fetch({
success: function() {
new App.Views.Index({ collection: documents });
},
error: function() {
new Error({ message: "Error loading documents." });
}
});
},
My View:
App.Views.Index = Backbone.View.extend({
initialize: function() {
console.log(this.documents);
this.documents = this.options.documents;
this.render();
},
render: function() {
if(this.documents.length > 0) {
var out = "<h3><a href='#new'>Create New</a></h3><ul>";
_(this.documents).each(function(item) {
out += "<li><a href='#documents/" + item.id + "'>" + item.escape('title') + "</a></li>";
});
out += "</ul>";
} else {
out = "<h3>No documents! <a href='#new'>Create one</a></h3>";
}
$(this.el).html(out);
$('#app').html(this.el);
}
});
The console.log of document code is: undefined
In the controller, var document is valid.
WHYYyY? How I can Access the json sent by the Controller in the view?
Thanks,
console.log(this.documents);
this.documents = this.options.documents;
Your using console.log before this.documents is even set.
UPDATE:
new App.Views.Index({ collection: documents });
this.documents = this.options.documents;
Wouldn't it be this.documents = this.options.collection; ? Because I don't see you passing the option.documents variable anywhere.
You pass collection: documents, so in your view you access it with this.collection.
Check out this jsfiddle that shows it working: http://jsfiddle.net/dira/TZZnA/
I dont know backbone too well ... but is this.documents defined before entering the initialize function ? seems not to be - try switching around the lines :
this.documents = this.options.documents; // define the variable
console.log(this.documents); // console log it
Related
I have added some functionality to my objects in draw2d canvas. such as :
var MyConnection= draw2d.Connection.extend({
init:function(attr){
this._super(attr);
this.setRouter(new draw2d.layout.connection.VertexRouter());
this.setOutlineStroke(1);
this.setOutlineColor("#000000");
this.setStroke(3);
this.setColor('#ffffff');
this.setRadius(150);
this.conectionResult={"src":{"nms":true,"trg":true},"trg":{"nms":true,"src":"true"}};
},
onContextMenu:function(x,y){
$.contextMenu({
selector: 'body',
events:{
hide:function(){ $.contextMenu( 'destroy' ); }
},
callback: $.proxy(function(key, options){
switch(key){
case "check":
result = this.checkConection();
this.conectionResult=result;
console.log(result);
if(result.src.trg && result.trg.src){
this.setColor("#FFFFFF");
}else{
this.setColor("#FF4422");
}
break;
case "report":
message=[];
result=this.conectionResult;
if(result.src.trg && result.trg.src){
alert("OK");
}else{
src=this.getSource();
trg=this.getTarget();
if(result.src.nms){
message.push("NMS Can See "+src.userData.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name);
}
}else{
message.push("NMS CAN NOT See "+trg.userData.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +"Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +"CAN NOT See "+trg.userData.dev_name+" Or NMS Can not confirm it");
}
}
if(result.trg.nms){
message.push("NMS Can See "+trg.userData.dev_name);
if(result.trg.src){
message.push(trg.userData.dev_name +" Can See "+src.usedData.dev_name);
}else{
message.push(trg.userData.dev_name +" CAN NOT See "+src.userData.dev_name);
}
}else{
message.push("NMS CAN NOT See "+trg.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name+" Or NMS Can not confirm it.");
}
}
alert(message.join("\n"));
}
break;
case "delete":
var cmd = new draw2d.command.CommandDelete(this);
this.getCanvas().getCommandStack().execute(cmd);
default:
break;
}
},this),
x:x,
y:y,
items:
{
"check":{name:"Check", icon:"edit"},
"report":{name:"Report",icon:"edit"},
"sep1": "---------"
,"delete": {name: "Delete", icon: "delete"}
}
});
},
checkConection:function(){
src=this.getSource();
trg=this.getTarget();
console.log("Source IP:"+src.userData.ip+", Target Ip:"+trg.userData.ip);
results={"src":{"nms":false,"trg":false},"trg":{"nms":false,"src":false}};
$.ajax({
url:"***/index.php?r=/******/check-conection&src="+src.userData.ip+"&trg="+trg.userData.ip,
async:false,
success: function(result){
results=result;
}
});
console.log(results);
this.conectionResult=results;
this.setConectionColor();
return results;
},
setConectionColor:function(){
result=this.conectionResult;
console.log(result);
if(result.src.trg && result.trg.src){
this.setColor("#FFFFFF");
}else{
this.setColor("#FF4422");
}
}
});
~
i used below method to save them via AJAX request in server.
function saveTopology(){
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas, function(json){
var jsonTxt = JSON.stringify(json,null,2); .
$("pre").text(jsonTxt);
});
alert($("pre").text());
draw2d=JSON.stringify(JSON.parse($("pre").html()));
var data={
id :1,
draw2d : draw2d,
map_id : 1
};
var url = "topology/save";
result = AjaxResponce(url,data,"POST");
$("pre").html(result);
displayJSON(canvas);
}
and used below to reload it for next times.
function setTopology(){
write2status("Requesting Topology of map_id 1 ...");
draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
var conn = new MyConnection({});
return conn;
};
var topology = AjaxResponce("topology/get-topology",{tplg_id:tplg_id});
console.log(topology);
data = topology;
var bg_map = "url('"+data.bg_map+"')";
var width = data.width;
var height = data.height;
var background_size = height+"px "+width+"px ";
if(typeof(data.draw2d)==="Array"){
$.each(data.draw2d,function(index,item){
if(typeof(item.userData) != "undefined" &&Object.keys(item.userData).length >0){
if(typeof(item.userData.dev_id) !== "undefined")
usedDevices.push(item.userData.dev_id);
}
});
}
topology=JSON.stringify(data.draw2d);
$(".ui-droppable").css({"background-image":bg_map});
$(".ui-droppable").css({"height":parseInt(height)*1.1});
$(".ui-droppable").css({"width":parseInt(width)*1.1});
write2status("Adding map to page...");
$("pre#json").html(topology);
write2status("Map added...");
}
I set
draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
var conn = new MyConnection({});
return conn;
};`
The functionalities works when i open a new form but nor added functionalities loads after reloading the page while they are asigned to any new objects that add to page after reload.
Can any one help me to solve this problem?
I've solve the problem but not sure is a correct way.
I just changed
var MyConnection= draw2d.Connection.extend({
in first code to
draw2d.Connection = draw2d.Connection.extend({
then removed related codes of 3th file. in this case Draw2d loads My connection instead of default function.
I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}
my searchform with backbone works.. except it always says that the item is not found so I think I always send an empty array so yes, then it's logic it won't find anything.
My searchresult view:
var ArtikelSearchResultsView = Backbone.View.extend({
el: '#searchResults',
render: function ( query_encoded ) {
var query = decodeURIComponent(query_encoded.replace(/\+/g, "%20"));
var result_artikels = _.filter(this.model.models, function (artikel_model) {
var artikel = artikel_model.attributes;
for (var key in artikel) {
if ( artikel[key].toLowerCase().indexOf( query.toLowerCase() ) >= 0 )
{
return true;
}
}
return false;
});
// Show results
var template = $("#search-results").html();
var result_html = _.template( template, { artikels: result_artikels, query: query } );
this.$el.html( result_html );
}
});
My router sends this:
searchResults: function(query){
artikelSearchView.render(query);
var artikelSearchResultsView = new ArtikelSearchResultsView({ model: Artikel });
artikelSearchResultsView.render(query);
}
Artikel is in this case:
var Artikel = Backbone.Model.extend({
urlRoot: 'api/items.json',
defaults: {
titel: 'Titel niet opgegeven',
url_titel: 'unieke sleutel urltitel',
img_path: 'geen image toegevoegd',
commentaar: 'Commentaar niet opgegeven',
categorie: 'Categorie niet opgegeven',
waardering: 0,
artikel: 'Artikel niet opgegeven'
},
initialize: function(){
if(!this.get('description')){
var lazy = 'This user was too lazy too add a description';
this.set('description', lazy);
}
}
});
Full code: http://pastebin.com/Y9zi6aGH (Awere that I use Artikel and Artikels in different ways, I know it's bad practice but that's the way I go for now) So my question is: Can someone fix me this so I get searchresult? If I press "a" that should give allmost all my objects but it gives me nothing in results.
I have made some changes to your code in order to work :
1- In your view ArtikelSearchResultsView, I have bound it's model (collection) reset event to it's render method, thus once it's model is reset from the server it call it's render method :
var ArtikelSearchResultsView = Backbone.View.extend({
el: '#searchResults',
initialize: function(){
this.model.bind('reset', this.render, this);
} ...
2- change
var artikels = new Artikels();
var artikel = new Artikels();
to
var artikels = new Artikels();
var artikel = new Artikel();
3- And finally change your router :
searchResults: function(query){
var artikelSearchResultsView = new ArtikelSearchResultsView({ model: artikels });
artikels.fetch();
}
I have also removed the filtering from ArtikelSearchResultsView render method in order to test it, now the 'this.model.models' is populated with the data you receive from the server.
I have written my javascript too much, and now the code keeps repeating itself, whereas I lack of knowledge on how to simplify matters. I have this idea of calling variable into function, but I don't know how to call this kind of function that contains dynamic variables.
Anyone got any tips on how can I achieve this?
var container = '#content_container';
function container_load(){
var data = $(this).attr('data');
var dataObject = {command : data};
var title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
container_load();
$(container).prepend(title);
});
});
Apparently, console returned ReferenceError: Can't find variable: dataObject
There is two issue is in your code
var container = '#content_container';
var title; //title should be declare as global,same as "container" variable
function container_load(dis){
var data = dis.attr('data');
var dataObject = {command : data};
title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
}
$(function(){
$('nav').on('click', 'a', function(){
container_load($(this)); //you have to pass the current element
$(container).prepend(title);
});
});
Demo : Demo
Try this :
var container = '#content_container';
function container_load(currElementId){
var data = $("#"+currElementId).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
var title = container_load(this.id);
$(container).prepend(title);
});
});
Here your problem is that you cannot 'this' in other function for that you need to pass it from your current function.
There seems to be few mistakes in your code, The scope is wrong and the data attribute is used not correctly I presume. I suppose this is what you wanted http://jsfiddle.net/EjEqK/2/
HTML
<nav >aaa</nav>
<div id="content_container"></div>
JS
function container_load() {
var data = $(this).data("val");
var dataObject = { command: data };
$("#content_container").prepend('<h2 data-val="' + dataObject.command + '">' + dataObject.command + '</h2>');
};
$(function () { $('nav > a').on('click', container_load); });
PS: If you don't need dataObject for anything else, directly use data
I think this will help you :
function container_load(currElement){
var data = $(currElement).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
}
$(function(){
var container = '#content_container';
$('nav')on.('click', 'a', function(){
var title = container_load(this);
$(container).prepend(title);
});
});
You could do the following :
var container = '#content_container',
title; // make title global
function container_load() {
var data = $(this).attr('data');
var dataObject = { command: data };
title = '<h2 data="' + dataObject.command + '">' +
dataObject.command + '</h2>';
};
$(function () {
$('nav') on.('click', 'a', function () {
container_load.call(this); // bind this to container_load
$(container).prepend(title);
});
});
But you could do even better :
$(function () {
$('nav') on.('click', 'a', function () {
var data = $(this).attr('data');
$('#content_container').prepend(
'<h2 data="' + data + '">' + data + '</h2>'
);
});
});
I have a enhancegrid which fields are editable. Some fields will be changed manually while others will change dynamically. The thing is that I would not want to store values onApplyEdit, I want to force save the values but I cant find the solution for it. Here is how it´s right now which actually working great.
dojo.connect(grid, "onApplyEdit", grid, function(evt, rowIndx, fieldIndx){
var selected_item = grid.getItem(evt);
//Not sure if this is the most efficient way but it worked for me
var row_id = grid.store.getValue(selected_item, "row_id");
var from_item_no = grid.store.getValue(selected_item, "from_item_no");
var from_inventory = grid.store.getValue(selected_item, "from_inventory");
var comment = grid.store.getValue(selected_item, "comment");
edit_quantity = grid.store.getValue(selected_item, "quantity");
var to_item_no = grid.store.getValue(selected_item, "to_item_no");
var to_inventory = grid.store.getValue(selected_item, "to_inventory");
var foundation = grid.store.getValue(selected_item, "foundation");
// Instantiate some write implementing store.
var store = grid.store;
// Set our load completed handler up...
var onCompleteFetch = function(items, request){
// Define the save callbacks to use
var onSave = function(){
dojo.xhrPost({
url: url,
content: {
row_id: row_id,
from_item_no: from_item_no,
from_inventory: from_inventory,
comment: comment,
quantity: edit_quantity,
to_item_no: to_item_no,
to_inventory: to_inventory,
foundation: foundation
},
handleAs: "text",
load: function(data){
console.log("Returned value: " + data);
global_saved_check = false;
},
error: function(error){
alert(error);
}
});// end xhrPost
} // end onSave
var onSaveError = function(error){
alert("Error occurred: " + error);
}
// If the store has modified items (it should), call save with the handlers above.
if(store.isDirty()){
store.save({onComplete: onSave, onError: onSaveError});
}
} // end onCompleteFetch
// Define a fetch error handler, just in case.
var onFetchError = function(error, request){
alert("Fetch failed. " + error);
}
// Fetch some data... All items with a foo attribute, any value.
store.fetch({query: {foo:"*"}, onComplete: onCompleteFetch});
});//end connect onApplyEdit