Knockout - load data into model with Ajax - not straight away - ajax

Here's a simplified example of my knockout model. The problem I'm having is that as soon as the page loads, the quiz is loaded. Why does it get run straight away and how can I stop it so that it only get's run when I want, say, on the click of a button?
Do I even need to use subscribe to do this?
HTML:
<h1>Test</h1>
<button class="btn btn-primary" data-bind="click: quizCount(quizCount() + 1)">
Click Me
</button>
<hr />
<div data-bind="visible: !loaded()">No Quiz</div>
<div data-bind="visible: loaded">Quiz Loaded!</div>
<hr />
<h3>Debug</h3>
<div data-bind="text: ko.toJSON(quizModel)"></div>
Javascript:
<script type="text/javascript">
var quizModel = { };
// DOM ready.
$(function () {
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
};
quizModel = new QuizViewModel();
quizModel.quizCount.subscribe(function (newCount) {
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
quizModel.questions(data.Questions);
}).complete(function () {
quizModel.loaded(true);
});
});
ko.applyBindings(quizModel);
})
</script>

Subscribe is only used for listening to changes in an observable so it will run immediately as soon as the observable gets a value.
You need to add this function to your viewmodel as a method, likely to be called getQuestions:
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
self.getQuestions = function(){
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
self.questions(data.Questions);
}).complete(function () {
self.loaded(true);
});
}
};
then you can easily have a button or something that binds to this method on click:
<button data-bind="click: getQuestions">Get questions</button>

Related

Dynamically Binding the the Oracle jet switcher slot to the oracle jet add and remove tab(Make switcher slot dynamic in oracle jet)

I want to make tab switcher auto decide the slot for the switcher but when I am trying to make it dynamic with the help of observable no data is showing the tab content area until I write the slot area statically. With observable variable, the slot is not getting the selected Slot value.
Please check how I can do this.
slot = [[selectedSlot]] //using for the slot value in html
this.selectedSlot = ko.observable('settings');
<div id="tabbardemo">
<oj-dialog class="tab-dialog hidden" id="tabDialog" dialog-title="Tab data">
<div slot="body">
<oj-form-layout>
<oj-input-text id="t1" value="{{newTabTitle}}" label-hint="Title"></oj-input-text>
</oj-form-layout>
</div>
<div slot="footer">
<oj-button id="idOK" on-oj-action="[[addTab]]">OK</oj-button>
<oj-button id="idCancel" on-oj-action="[[closeDialog]]">Cancel</oj-button>
</div>
</oj-dialog>
<oj-button id="addTab" on-oj-action="[[openDialog]]">Add Tab</oj-button>
<br/>
<br/>
<oj-tab-bar contextmenu="tabmenu" id="hnavlist" selection="{{selectedItem}}" current-item="{{currentItem}}" edge="top" data="[[dataProvider]]"
on-oj-remove="[[onRemove]]">
<template slot="itemTemplate" data-oj-as="item">
<li class="oj-removable" :class="[[{'oj-disabled' : item.data.disabled}]]">
<a href="#">
<oj-bind-text value="[[item.data.name]]"></oj-bind-text>
</a>
</li>
</template>
<oj-menu slot="contextMenu" class="hidden" aria-label="Actions">
<oj-option data-oj-command="oj-tabbar-remove">
Removable
</oj-option>
</oj-menu>
</oj-tab-bar>
<oj-switcher value="[[selectedItem]]">
<div slot="[[selectedSlot]]"
id="home-tab-panel"
role="tabpanel"
aria-labelledby="home-tab">
<div class="demo-tab-content-style">
<h2>Home page content area</h2>
</div>
</div>
<div slot="tools"
id="tools-tab-panel"
role="tabpanel"
aria-labelledby="tools-tab">
<div class="demo-tab-content-style">
<h1>Tools Area</h1>
</div>
</div>
<div slot="base"
id="base-tab-panel"
role="tabpanel"
aria-labelledby="ba`enter code here`se-tab">
<div class="demo-tab-content-style">
<h1>Base Tab</h1>
</div>
</div>
</oj-switcher>
<br>
<div>
<p class="bold">Last selected list item:
<span id="results">
<oj-bind-text value="[[selectedItem]]"></oj-bind-text>
</span>
</p>
</div>
</div>
JS code below
require(['ojs/ojcontext',
'knockout',
'ojs/ojbootstrap',
'ojs/ojarraydataprovider',
'ojs/ojknockout',
'ojs/ojnavigationlist',
'ojs/ojconveyorbelt',
'ojs/ojdialog',
'ojs/ojbutton',
'ojs/ojinputtext',
'ojs/ojformlayout',
'ojs/ojswitcher',
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
this.data = ko.observableArray([{
name: 'Settings',
id: 'settings'
},
{
name: 'Tools',
id: 'tools'
},
{
name: 'Base',
id: 'base'
}
]);
this.selectedSlot = ko.observable('settings'); //Sepecifically mentioned to show what it is the objective
this.dataProvider = new ArrayDataProvider(this.data, { keyAttributes: 'id' });
this.selectedItem = ko.observable('settings');
this.currentItem = ko.observable();
this.tabCount = 0;
this.newTabTitle = ko.observable();
this.delete = (function (id) {
var hnavlist = document.getElementById('hnavlist');
var items = this.data();
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
this.data.splice(i, 1);
Context.getContext(hnavlist)
.getBusyContext()
.whenReady()
.then(function () {
hnavlist.focus();
});
break;
}
}
}).bind(this);
this.onRemove = (function (event) {
this.delete(event.detail.key);
event.preventDefault();
event.stopPropagation();
}).bind(this);
this.openDialog = (function () {
this.tabCount += 1;
this.newTabTitle('Tab ' + this.tabCount);
document.getElementById('tabDialog').open();
}).bind(this);
this.closeDialog = function () {
document.getElementById('tabDialog').close();
};
this.addTab = (function () {
var title = this.newTabTitle();
var tabid = 'tid' + this.tabCount;
this.data.push({
name: title,
id: tabid
});
this.closeDialog();
}).bind(this);
}
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
}
);
It is a bit complex to understand when you copy from JET cookbook. You have done almost everything right. Just make the following changes:
1) Remove this:
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
Why? The bootstrapping is required once per application, which is done inside your main.js file.
2) Replace require by define
Why? Require block is again maintained in main.js, where your required modules are pre-loaded. All subsequent viewModels have define block
3) Return an instance of your ViewModel
define([
... Your imports
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
// Your code
}
return ViewModel;
});

Load content into bootstrap popover using angular and ajax don't work

I am trying to populate a content into an bootstrap popover using angular and ajax. Although the data have been loaded correctly (as i can see in console.log) the result don't appear in the popover's content. I think the angular's loading is not ready yet when the bootstrap popover is loaded. Thus, how can i populate this popover immediately after angular load?
This is the code:
$(function() {
var p = $("#popover").popover({
content: $("#popover-content").html(),
html: true
});
});
(function () {
var app = angular.module("ng-app", []);
app.controller("NotificationsController", function ($scope, $http) {
$scope.links = [];
$scope.load = function () {
$http.get("json.php").success(function (response) {
console.log(response);
$scope.links = response;
// the response return is somethin like
// [
// {title: "Google", url: "http://www.google.com"},
// {title: "Gmail", url: "http://www.google.com"},
// ]
});
};
$scope.load();
});
})();
<ul class="nav navbar-nav">
<li data-ng-controller="NotificationsController as notification">
<a href="#" data-toggle="popover" id="popover" title="Notificações" data-placement="bottom" data-trigger="focus">
<span class="badge">{{links.length}}</span>
</a>
<div id="popover-content" style="display: none">
<div data-ng-repeat="link in links">
{{link.title}}
</div>
</div>
</li>
</ul>
Thanks in advance
You can put your function inner the controller, to get angular cycle. And, also, define your jquery call on a $timeout event.
Please look this sample on jsbin: jsbin
controller('c', function($scope, $timeout) {
$scope.getData = function() {
return $("#popover-content").html();
};
$timeout(function() {
$("#popover").popover({
content: $scope.getData,
html: true
});
});
}

ng-grid in from tag with run at server in aspx page

i am calling the ajax function on click of button it returns the json data and i am passing the data to the main.js script file(controller) its getting the data and binding the data to the ng-grid, the question here is whne i put the ng-grid in the from tag it does not dispaly the data
<script type="text/javascript">
$(document).ready(function () {
$("#mybutton").click(function () {
var scope = angular.element(document.getElementById("wrap")).scope(); // to get access all the varibales defined in the contoller
scope.$apply(function () {
$.ajax({
type: "POST",
url: "Website/Nggrid.asmx/GetDataForNgGrid",
success: function (result) {
// console.log(result);
var fd = JSON.parse(result); //parsing the json string
scope.updateMessage(fd);
alert("hi");
},
error: function (xmlhttprequest, Status, thrownError) {
alert(thrownError.toString());
alert(thrownError);
}
});
});
});
});
</script>
this is the function i am calling when the user clicks on button
<body ng-controller="MyCtrl">
<%--<form id="form1" runat="server">--%>
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
<%-- </form>--%>
</body>
this is the main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [];
$scope.updateMessage = function (_s) {
$scope.myData = _s;
// $scope.Enable = true;
};
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{ field: 'Status', displayName: 'Status', width: "*" }
]
};
});
my question is here that when i put ng-grid in the from tag it wont show the data, please give the suggestion on this
<form id="form1" runat="server">
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
</form>

Backbonejs Marionette simple chat example

As a marionnette beginner, I am trying to make a simple chat application using Collection and CollectionViews.
My collection won't have a fetch method since the messages only come from a particular event.
In the piece of code below my click event is not catched and I wonder why.
Should the 'send message' event be handled by the Collection view ?
Do I need to call App.chat.show(MsgListView) to display the messages ?
TBox.module("ChatApp", function(ChatApp, App, Backbone, Marionette, $, _) {
App.addRegions({
chat: "#chat-messages",
});
// Models
// ------
MsgEntry = Backbone.Model.extend({});
// Collections
// -----------
MsgCollection = Backbone.Collection.extend({
model: MsgEntry
})
// VIews
// -----
MsgView = Backbone.Marionette.ItemView.extend({
template: '#chat-entry-template',
});
MsgListView = Backbone.Marionette.CollectionView.extend({
itemView: MsgView,
events: {
"click #chat-send-btn": "handleNewMessage"
},
handleNewMessage: function(data) {
console.log("CLICK" + data);
},
});
// Init & Finalize
// ---------------
ChatApp.addInitializer(function() {
var msgCollection = new MsgCollection({});
var msgEntry = new MsgEntry({'msg': 'Hello World'});
msgCollection.add(msgEntry);
var msgListView = new MsgListView({collection: msgCollection});
});
});
HTML template
<body>
<!-- templates -->
<script type="text/template" id="status-view-template">
<div>Connecting ...</div>
</script>
<script type="text/template" id="chat-entry-template">
Hello <%= msg =>
</script>
<div id="app">
<div id="sidebar">
<div id="chat">
<h3>Chat</h3>
<div id="chat-messages">
</div>
<div id-"chat-input">
<input type="text" name="msg" />
<button id="chat-send-btn">Send</button>
</div>
</div>
</div>
<!-- main -->
<div id="page">
</div>
<div>
</body>
Ok I made it work with App.chat.show(msgListView);
Also the events hash only takes car of the ItemView events, not other dom events.
// Init & Finalize
// ---------------
ChatApp.addInitializer(function() {
App.vent.trigger("app:started", "ChatApp");
var msgCollection = new MsgCollection([{foo :'bar', foo: 'lol'}]);
var msgListView = new MsgListView({collection: msgCollection});
// render and display the view
App.chat.show(msgListView);
});

Backbone View Events Firing for Each Instance of a View

A have a parent view OpenOrderListView that creates instances of OpenOrderViews that have events on them. The result I'm trying to gain is when the markCompleted button of an OpenOrderView is clicked a function be called to tell the model to set that attribute.
The functionality is working but it is being called on all OpenOrderViews inside the parent (OpenOrderListView) instead of just the view in which the click event was handled. How can I make this event only trigger on the view that was acted upon?
Code is below
window.OpenOrderListView = Backbone.View.extend({
el: 'table.openOrders tbody',
initialize: function() {
_.bindAll(this,'render');
this.render();
},
render : function() {
var $openOrders
var models = this.collection.open();
for (var i = models.length - 1; i >= 0; i--) {
console.log('model', models[i]);
console.log("this.template", this.template);
new OpenOrderView({'model': models[i], 'el': this.el});
};
}
});
window.OpenOrderView = Backbone.View.extend({
initialize: function() {
console.log('this', this);
_.bindAll(this,'render',
'markCompleted',
'markInProgress');
this.render();
},
events : {
"click .markCompleted": "markCompleted",
"click .markInProgress": "markInProgress",
},
markCompleted: function(){
console.log(this);
this.model.markCompleted();
},
markInProgress: function(){
console.log("markInProgress",this);
this.model.markInProgress();
console.log('markInProgress Complete');
},
template : 'template-openOrderView',
render : function() {
console.log("View Rendered");
$(this.el).append(tmpl(this.template, this.model.toJSON()));
}
window.Order = Backbone.Model.extend({
url: function(){
return "/api/order/id/"+this.get("id");
},
isCompleted: function(){
return this.get('status') == "completed";
},
isInProgress: function(){
return this.get('status') == "inProgress";
},
isOpen: function(){
return this.get('status') == "open";
},
markCompleted: function(){
this.set({'status':"completed"});
console.log('markCompleted');
return this.save();
},
markInProgress: function(){
this.set({'status':"inProgress"});
console.log('markInProgress');
return this.save();
},
markOpen: function(){
this.set({'status':"open"});
console.log('markOpen');
return this.save();
}
});
})
OrderView Template
<tr class="order">
<td class="preview hide_mobile">
<img src="{%=o.thumbnail_url%}">
</td>
<td class="name">
{%=o.name%}
</td>
<td class="description"><span>{%=o.description%}</span></td>
<td class="hide_mobile date_added"><span>{%=o.date_added%}</span></td>
<td class="hide_mobile user"><span>{%=o.username%}</span></td>
<td class="status">
<a class="btn modal-download" target="_blank" href="{%=o.url%}" title="{%=o.name%}" download="{%=o.name%}">
<i class="icon-download"></i>
<span>Download</span>
</a>
<button class="markCancel btn btn-danger" data-type="{%=o.delete_type%}" data-url="{%=o.delete_url%}">
<i class="icon-remove icon-white"></i>
<span>Cancel</span>
</button>
<button class="markInProgress btn btn-primary" data-type="" data-url="">
<i class="icon-repeat icon-white"></i>
<span>Mark In Progress</span>
</button>
<button class="markCompleted btn btn-success" data-type="" data-url="">
<i class="icon-ok icon-white"></i>
<span>Mark Completed</span>
</button>
</td>
All the SubViews are sharing the same DOM element table.openOrders tbody. This is done in the line new OpenOrderView({'model': models[i], 'el': this.el});.
So when you declare events like this:
events : {
"click .markCompleted": "markCompleted"
}
What is happening is that all DOM elements that match this table.openOrders tbody .markCompleted will be binded with this click event.
You need each SubView to have each own this.el DOM element.
In your case I think is better if your SubViews create theirs own DOM element in the air like this:
// code simplified an not tested
window.OpenOrderView = Backbone.View.extend({
tagName: 'tr',
attributes: { class: "order" },
initialize: function(){
// don't render() here
},
// ... rest of your code
render: function(){
this.$el.html(tmpl(this.template, this.model.toJSON()));
return this;
}
})
Look that now the SubView is not rendering itself, neither appending its DOM element directly to the page, it will be a job for the ParentView:
// code simplified an not tested
window.OpenOrderListView = Backbone.View.extend({
render : function() {
var $openOrders
var models = this.collection.open();
for (var i = models.length - 1; i >= 0; i--) {
var openOrderView = new OpenOrderView({'model': models[i]});
this.$el.append( openOrderView.render().el );
};
});
I think this is a very common pattern.
PD: You have to modify your template removing the tr open/close.

Resources