Can't render template into div - javascript

I need to render my template templates/page.html:
<section class="section">
<div class="container">
<h1 class="title"><%= title %></h1>
<div><%= content %></div>
<div><%= pages %></div>
</div>
</section>
into my div element with page-content id:
// Underscore mixins
_.mixin({templateFromUrl: function (url, data, settings) {
var templateHtml = "";
this.cache = this.cache || {};
if (this.cache[url]) {
templateHtml = this.cache[url];
} else {
$.ajax({
url: url,
method: "GET",
async: false,
success: function(data) {
templateHtml = data;
}
});
this.cache[url] = templateHtml;
}
return _.template(templateHtml, data, settings);
}});
// Models
var PageState = Backbone.Model.extend({
defaults: {
title: "",
subtitle: "",
content: "",
pages: "",
state: "games"
}
});
var pageState = new PageState();
// Routers
var PageRouter = Backbone.Router.extend({
routes: {
"": "games",
"!/": "games",
"!/games": "games",
"!/users": "users",
"!/add-user": "add_user"
},
games: function () {
select_item($("#games"));
console.log("games");
pageState.set({ state: "games" });
},
users: function () {
select_item($("#users"));
console.log("users");
pageState.set({ state: "users" });
},
add_user: function () {
console.log("add_user");
}
});
var pageRouter = new PageRouter();
// Views
var Page = Backbone.View.extend({
templates: {
"page": _.templateFromUrl("/templates/page.html")
},
initialize: function () {
this.render();
},
render: function () {
var template = this.templates["page"](this.model.toJSON());
this.$el.html(template);
return this;
}
});
$(function () {
var page = new Page({
el: '#page-content',
model: pageState
});
});
// Run backbone.js
Backbone.history.start();
// Close mobile & tablet menu on item click
$('.navbar-item').each(function(e) {
$(this).click(function() {
if($('#navbar-burger-id').hasClass('is-active')) {
$('#navbar-burger-id').removeClass('is-active');
$('#navbar-menu-id').removeClass('is-active');
}
});
});
// Open or Close mobile & tablet menu
$('#navbar-burger-id').click(function () {
if($('#navbar-burger-id').hasClass('is-active')) {
$('#navbar-burger-id').removeClass('is-active');
$('#navbar-menu-id').removeClass('is-active');
} else {
$('#navbar-burger-id').addClass('is-active');
$('#navbar-menu-id').addClass('is-active');
}
});
// Highlights an item in the main menu
function select_item(sender) {
$("a.v-menu-item").removeClass("is-active");
sender.addClass("is-active");
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<body>
<section class="hero is-primary is-medium">
<div class="hero-head">
<nav id="navMenu" class="navbar">
<div class="container">
<div class="navbar-brand">
<a class="navbar-item is-size-2">Virto</a>
<span id="navbar-burger-id" class="navbar-burger burger" data-target="navbar-menu-id">
<span></span>
<span></span>
<span></span>
</span>
</div>
<div id="navbar-menu-id" class="navbar-menu">
<div class="navbar-end">
<a id="games" href="#!/games" class="navbar-item v-menu-item is-active">Games</a>
<a id="users" href="#!/users" class="navbar-item v-menu-item">Users</a>
<span class="navbar-item">
<a href="#!/add-user" class="button is-primary is-inverted">
<span class="icon">
<i class="fas fa-user-circle"></i>
</span>
<span>Add user</span>
</a>
</span>
<div>
</div>
</div>
</nav>
</div>
</section>
<div id="page-content"></div>
</body>
But my content doesn't load... I'm a noobie in backbone.js still so can someone explain what do I doing wrong and how to fix?
ADDED
I have checked my script in debugger. It loads a template and finds my div in the render() function but I can't see any result in browser after, my div is empty still.

I created a plunker with your code, and it works fine for me: link
I think you only forgot to initialize your model:
// Models
var PageState = Backbone.Model.extend({
defaults: {
title: "Title - 1",
subtitle: "Subtitle - 1",
content: "Content",
pages: "1",
state: "games"
}
});

Related

Vue method not passing data to array of objects

So I'm going to be explaining this in the best way possible as I don't understand what might be causing this issue on my end as I feel like I've followed all of the directions and keep hitting a brick wall.
Here is my vue.js app:
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
const default_apps = [
{
'post_title': 'Excel',
}, {
'post_title': 'Word',
}, {
'post_title': 'SharePoint',
}];
console.log(default_apps);
const default_apps1 = this.get_array_of_post_objects('application_launcher');
console.log(default_apps1);
return {
available_list: [],
selected_list: default_apps.map(function(name, index) {
return {
name: name.post_title,
order: index + 1,
fixed: false
};
}),
}
},
methods: {
get_array_of_post_objects(slug) {
let items = [];
wp.api.loadPromise.done(function () {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
items.push(...posts.items);
});
});
return items;
},
},
computed: {
dragOptions() {
// Pass in additional <draggable> options inside the return for both lists.
return {
tag: 'div',
group: 'o365apps',
disabled: !this.editable,
ghostClass: "ghost",
};
},
},
});
Inside my methods, I have a method called get_array_of_post_objects which returns an array of objects that I'm pulling through.
So inside data, I'm console logging my manual default_apps and my default_apps1 which is the method. Both of the arrays of objects have post_title: "something" inside.
Here is the return that I'm getting:
Inside my mapping, when I define default_apps, my IDE returns some result for name but when I switch it over to default_apps1, it's not finding any results as shown below:
I don't know what else to look at - All help would be appreciated!
Here is the HTML code if that is needed:
<div class="column is-half-desktop is-full-mobile buttons">
<nav class="level is-mobile mb-0">
<div class="level-left">
<div class="level-item is-size-5 has-text-left">Selected</div>
</div>
<div class="level-right">
<div class="level-item" #click="orderList()"><i class="fas fa-sort-alpha-up is-clickable"></i></div>
</div>
</nav>
<hr class="mt-1 mb-3">
<!-- Decorator: # also known as v-on: -->
<!-- Bind: : also known as v-bind: -->
<draggable class="list-group"
v-model="selected_list"
v-bind="dragOptions"
:move="onMove"
#add="onAdd"
#remove="onRemove"
#start="isDragging=true"
#end="isDragging=false">
<button class="button is-fullwidth is-flex list-group-item o365_app_handle level is-mobile" v-for="(app, index) in selected_list" :key="app.order">
<div class="level-left">
<span class="icon" aria-hidden="true">
<img :src="`<?= Path::o365('${app.name}' . '.svg'); ?>'`" />
</span>
<span>{{app.name}}</span>
</div>
<div class="level-right is-hidden-desktop">
<span class="icon has-text-danger is-clickable" #click="remove(index)">
<i class="fas fa-times"></i>
</span>
</div>
</button>
</draggable>
</div>
I'm not 100% sure what your app is supposed to do, so modify it for your needs.
Here the selected_list will be empty first.
Then we call your method, which is asynchronous, and once it's done selected_list gets populated.
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
return {
available_list: [],
selected_list: [],
}
},
created() {
this.get_array_of_post_objects("add-your-slug")
},
methods: {
get_array_of_post_objects(slug) {
wp.api.loadPromise.done(function() {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
// You might want to modify posts for your needs
this.selectedList = posts
});
});
},
},
});

How to calculate grand total from a list

I'm making an POS application on mobile phone and I have a question. How do I calculate the grand total from the list of item from the database?
Here's my code
order-detail.dxview
POSApp.OrderDetail = function (params, viewInfo) {
"use strict";
var id = params.id,
order = new POSApp.OrderViewModel(),
isReady = $.Deferred(),
// Item List
shouldReload = false,
dataSourceObservable = ko.observable(),
dataSource;
function handleViewShown() {
POSApp.db.Orders.byKey(id).done(function (data) {
order.fromJS(data);
isReady.resolve();
});
// Item List
if (!dataSourceObservable()) {
dataSourceObservable(dataSource);
dataSource.load().always(function () {
isReady.resolve();
});
}
else if (shouldReload) {
refreshList();
}
// Item List
}
// Item List
function handleViewDisposing() {
POSApp.db.OrderDetails.off("modified", handleOrderDetailsModification);
}
function handleOrderDetailsModification() {
shouldReload = true;
}
// Item List
dataSource = new DevExpress.data.DataSource({
store: POSApp.db.OrderDetails,
map: function (item) {
return new POSApp.OrderDetailViewModel(item);
},
expand: ["Item"],
sort: { field: "OrderDetailId", desc: false },
filter: ["OrderId", parseInt(id)]
});
POSApp.db.OrderDetails.on("modified", handleOrderDetailsModification);
var viewModel = {
grandTotal: ko.observable(total),
handleDelete: function () {
DevExpress.ui.dialog.confirm("Are you sure you want to delete this item?", "Delete item").then(function (result) {
if (result)
handleConfirmDelete();
});
},
handleConfirmDelete: function () {
POSApp.db.Orders.remove(id).done(function () {
if (viewInfo.canBack) {
POSApp.app.navigate("Orders", { target: "back" });
}
else {
POSApp.app.navigate("Blank", { target: "current" });
}
});
},
//Item List
refreshList: function () {
shouldReload = false;
dataSource.pageIndex(0);
dataSource.load();
},
//Item List
// Return
id: id,
order: order,
viewShown: handleViewShown,
isReady: isReady.promise(),
// Item List
dataSource: dataSourceObservable,
viewDisposing: handleViewDisposing,
// Item List
// Return
};
return viewModel;
};
order-detail.js
<div data-options="dxView : { name: 'OrderDetail', title: 'Order' } " >
<div data-bind="dxCommand: { onExecute: '#OrderEdit/{id}', direction: 'none', id: 'edit', title: 'Edit', icon: 'edit' }"></div>
<div data-bind="dxCommand: { onExecute: handleDelete, id: 'delete', title: 'Delete', icon: 'remove' }"></div>
<div data-options="dxContent : { targetPlaceholder: 'content' } " class="dx-detail-view dx-content-background" data-bind="dxDeferRendering: { showLoadIndicator: true, staggerItemSelector: 'dx-fieldset-header,.dx-field', animation: 'detail-item-rendered', renderWhen: isReady }" >
<div data-bind="dxScrollView: { }">
<div class="dx-fieldset">
<div class="dx-fieldset-header" data-bind="text: order.PhoneNumber"></div>
<div class="dx-field">
<div class="dx-field-label">Order id</div>
<div class="dx-field-value-static" data-bind="text: order.OrderId"></div>
</div>
<div class="dx-field">
<div class="dx-field-label">Phone number</div>
<div class="dx-field-value-static" data-bind="text: order.PhoneNumber"></div>
</div>
<div class="dx-field">
<div class="button-info" data-bind="dxButton: { text: 'Add Item', onClick: '#AddItem/{id}', icon: 'add', type: 'success' }"></div>
<!-- Item List -->
<div data-bind="dxList: { dataSource: dataSource, pullRefreshEnabled: true }">
<div data-bind="dxAction: '#OrderDetailDetails/{OrderDetailId}'" data-options="dxTemplate : { name: 'item' } ">
<!--<div class="list-item" data-bind="text: Item().ItemName"></div>
<div class="list-item" style="float:right;" data-bind="text: Amount"></div>-->
<div class="item-name" data-bind="text: Item().ItemName"></div>
<div class="item-amount" data-bind="text: Amount"></div>
<div class="clear-both"></div>
</div>
</div>
</div>
<div class="dx-field">
<div class="dx-field-label">Grand total</div>
<!--<div class="dx-field-value-static" data-bind="text: order.GrandTotal"></div>-->
<div class="dx-field-value-static" data-bind="text: grandTotal"></div>
</div>
</div>
<div data-options="dxContentPlaceholder : { name: 'view-footer', animation: 'none' } " ></div>
</div>
</div>
</div>
I've tried by using get element by class name and it still doesn't work.
I've tried by using get element by class name and it still doesn't work.
You shouldn't try to get the data from your view; it's already in your viewmodel!
This documentation page tells me you can get an array of items from your DataSource instance by calling the items method.
From your data source's map function and your text: Amount data-bind, I figured each item probably has an Amount property which holds an integer.
grandTotal can be a computed that adds these values together whenever dataSourceObservable changes:
grandTotal: ko.computed(function() {
var total = 0;
var currentDS = dataSourceObservable();
if (currentDS) {
var currentItems = currentDS.items();
total = currentItems.reduce(function(sum, item) {
return sum + item.Amount;
}, total);
}
return total;
});
Here, the source is a Knockout observable array and the dxList data source. A value of grand totals is stored in the 'total' variable which is a computed observable depending on 'source'. So, once 'source' is changed, 'total' is re-calculated as well.
var grandTotal = ko.observable(0);
dataSource = new DevExpress.data.DataSource({
// ...
onChanged: function () {
grandTotal(0);
var items = dataSource.items();
for (var i = 0; i < items.length; i++) {
grandTotal(grandTotal() + items[i].Amount());
}
}
});
return {
// ...
grandTotal: grandTotal
};

Adding child routes in ember.js

I'm working on ember.js tutorial now. I got a problem on "adding child routes" chapter. My todos list is not displayed. The "todos" template outputing just fine but "todos/index" template doesn't work at all. The console does not show any errors. I guess that this is some local problem or some bug. Maybe someone has already met with a similar problem. What could be the reason of this issue? How can i solve it?
Thanks.
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Ember.js • TodoMVC</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/x-handlebars" data-template-name="todos/index">
<ul id="todo-list">
{{#each itemController="todo"}}
<li {{bind-attr class="isCompleted:completed isEditing:editing"}}>
{{#if isEditing}}
{{edit-todo class="edit" value=title focus-out="acceptChanges" insert-newline="acceptChanges"}}
{{else}}
{{input type="checkbox" checked=isCompleted class="toggle"}}
<label {{action "editTodo" on="doubleClick"}}>{{title}}</label><button {{action "removeTodo"}} class="destroy"></button>
{{/if}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="todos">
<section id="todoapp">
<header id="header">
<h1>todos</h1>
{{input type="text" id="new-todo" placeholder="What needs to be done?"
value=newTitle action="createTodo"}}
</header>
<section id="main">
{{outlet}}
<input type="checkbox" id="toggle-all">
</section>
<footer id="footer">
<span id="todo-count">
<strong>{{remaining}}</strong> {{inflection}} left</span>
<ul id="filters">
<li>
All
</li>
<li>
Active
</li>
<li>
Completed
</li>
</ul>
<button id="clear-completed">
Clear completed (1)
</button>
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
</footer>
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.2.0.js"></script>
<script src="js/libs/ember-data.js"></script>
<script src="js/app.js"></script>
<script src="js/route.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/controllers/todo_controller.js"></script>
<script src="js/controllers/todos_controller.js"></script>
<script src="js/views/edit_todo_view.js"></script>
</body>
</html>
JS:
window.Todos = Ember.Application.create();
Todos.ApplicationAdapter = DS.FixtureAdapter.extend();
Todos.Router.reopen({
rootURL: '/one/'
});
Todos.Router.map(function () {
this.resource('todos', { path: '/' });
});
Todos.TodosRoute = Ember.Route.extend({
model: function () {
return this.store.find('todo');
}
});
Todos.TodosIndexRoute = Ember.Route.extend({
model: function () {
return this.modelFor('todos');
}
});
Todos.Todo = DS.Model.extend({
title:DS.attr('string'),
isCompleted:DS.attr('boolean')
});
Todos.Todo.FIXTURES = [
{
id: 1,
title: 'Learn Ember.js',
isCompleted: true
},
{
id: 2,
title: '...',
isCompleted: false
},
{
id: 3,
title: 'Profit!',
isCompleted: false
}
];
Todos.TodosController = Ember.ArrayController.extend({
actions: {
createTodo: function () {
// Get the todo title set by the "New Todo" text field
var title = this.get('newTitle');
if (!title.trim()) { return; }
// Create the new Todo model
var todo = this.store.createRecord('todo', {
title: title,
isCompleted: false
});
// Clear the "New Todo" text field
this.set('newTitle', '');
// Save the new model
todo.save();
}
},
remaining: function () {
return this.filterBy('isCompleted', false).get('length');
}.property('#each.isCompleted'),
inflection: function () {
var remaining = this.get('remaining');
return remaining === 1 ? 'item' : 'items';
}.property('remaining'),
});
Todos.TodoController = Ember.ObjectController.extend({
actions:{
editTodo: function () {
this.set('isEditing', true);
},
acceptChanges: function () {
this.set('isEditing', false);
if (Ember.isEmpty(this.get('model.title'))) {
this.send('removeTodo');
} else {
this.get('model').save();
}
},
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
},
},
isEditing: false,
isCompleted: function(key, value){
var model = this.get('model');
if (value === undefined) {
// property being used as a getter
return model.get('isCompleted');
} else {
// property being used as a setter
model.set('isCompleted', value);
model.save();
return value;
}
}.property('model.isCompleted')
});
Technically this isn't a bug, the team figured there is no point in having an index route if you can't go any deeper in the router (this is due to the fact that the todos route and template will render, so there is no real need for the index route. That being said, if you really want it, add an anonymous function and you'll get it.
Todos.Router.map(function () {
this.resource('todos', { path: '/' },function () {});
});
https://github.com/emberjs/ember.js/issues/3995
I had this problem too. After much perplexity, the solution was to use a version of index.html that actually had the <script> wrapped <ul>, instead of the one where I was moving that block around to see if it made a difference and ended up having it nowhere.

Why all but 1 Route is working with Backbone Router

In the script below are various routes and view and routes events built with Backbone.js
Why is it, that all of the routes work as I expect except the last one 'products'.
I originally had it as a very different function but realized it wasn't firing off, but not even as a duplicate of the other views and routes it still wont work.
Anyone have an idea why?
Thanks you!
I am also very new to Backbone.
Rich
<!doctype html>
<html>
<head>
<title>Undie Couture by Lauren Copeland</title>
<link type="text/css" rel="stylesheet" href="/assets/css/museosans_500_macroman/stylesheet.css" />
<link type="text/css" rel="stylesheet" href="/assets/css/bootstrap/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/assets/css/site/front-styles.css" />
</head>
<body>
<div id="wrapper">
<div class="content">
<header>
<div class="container">
<div id="logo"></div>
<nav>
<ul>
<li>shop</li>
<li>contact</li>
<li>about</li>
<li>wholesale</li>
</nav>
</nav>
</div>
</header>
<div class="container">
<div class="page" id="first" style="display:none;"></div>
<div class="page"></div>
</div>
</div>
</div>
</body>
<script type="text/template" id="title-temp">
<%= title %>
</script>
<script type="text/template" id="logo-temp">
<img src="/assets/img/logo-strip.png" />
</script>
<script type="text/template" id="home-temp">
<%= title %>
</script>
<script type="text/template" id="page-temp">
<h1><%= page.pluck('title') %></h1>
<div id="body">
<%= page.pluck('body') %>
</div>
</script>
<script type="text/template" id="product-temp">
<h1><%= page.pluck('name') %></h1>
<div id="body">
<%= page.pluck('description') %>
</div>
</script>
<script type="text/javascript" src="/assets/js/libs/jquery/jquery.js"> </script>
<script type="text/javascript" src="/assets/js/libs/underscore/underscore.js"></script>
<script type="text/javascript" src="/assets/js/libs/backbone/backbone-min.js"></script>
<script type="text/javascript" src="/assets/js/libs/bootstrap/bootstrap.js"></script>
<script type = "text/javascript">
var Router = Backbone.Router.extend({
routes: {
"home": "home",
"about": "about",
"contact": "contact",
"wholesale": "wholesale",
"products": "products"
}
});
var Page = Backbone.Model.extend({
initialize: function() {
console.log('Page model loaded');
},
defaults: {
"id": "",
"title": "",
"body": "",
"slug": ""
},
urlRoot: '/backbone/page'
});
var Pages = Backbone.Collection.extend({
initialize: function() {
console.log('pages collection loaded');
},
url: '/backbone/page'
});
var HomeView = Backbone.View.extend({
template: $('#standard').html(),
el: '.page:first',
change: function() {
$('.page').fadeOut('slow');
},
render: function() {
logo = $('#logo-temp').html();
$('#logo').html(logo);
$('.content').attr('id', 'home');
var that = this;
that.change();
compiled = _.template($('#home-temp').html(), {
title: ''
});
that.$el.html(compiled);
}
});
var AboutView = Backbone.View.extend({
template: $('#standard').html(),
el: '.page:first',
change: function() {},
render: function() {
console.log('render')
var that = this;
logo = $('#logo-temp').html();
$('#logo').html(logo);
$('.content').attr('id', 'about');
aboutPage = new Pages();
aboutPage.fetch({
data: {
id: 3
},
success: function() {
$('#first').fadeOut({
duration: 400,
complete: function() {
console.log(aboutPage.models)
compiled = _.template($('#page-temp').html(), {
page: aboutPage
});
that.$el.html(compiled).delay(300).fadeIn();
}
});
}
});
}
});
var ContactView = Backbone.View.extend({
template: $('#standard').html(),
el: '.page:first',
change: function() {
$('.page').fadeOut();
},
render: function() {
var that = this;
logo = $('#logo-temp').html();
$('#logo').html(logo);
$('.content').attr('id', 'contact');
contactPage = new Pages();
contactPage.fetch({
data: {
id: 2
},
success: function() {
$('#first').fadeOut({
duration: 400,
complete: function() {
console.log(contactPage.models)
compiled = _.template($('#page-temp').html(), {
page: contactPage
});
that.$el.html(compiled).delay(300).fadeIn();
}
});
}
});
}
});
var WholesaleView = Backbone.View.extend({
template: $('#standard').html(),
el: '.page:first',
change: function() {},
render: function() {
console.log('render')
var that = this;
logo = $('#logo-temp').html();
$('#logo').html(logo);
$('.content').attr('id', 'about');
wholePage = new Pages();
wholePage.fetch({
data: {
id: 4
},
success: function() {
$('#first').fadeOut({
duration: 400,
complete: function() {
console.log(wholePage.models)
compiled = _.template($('#page-temp').html(), {
page: wholePage
});
that.$el.html(compiled).delay(300).fadeIn();
}
});
}
});
}
});
var ProductView = Backbone.View.extend({
template: $('#standard').html(),
el: '.page:first',
change: function() {},
render: function() {
var that = this;
logo = $('#logo-temp').html();
$('#logo').html(logo);
$('.content').attr('id', 'about');
wholePage = new Pages();
wholePage.fetch({
data: {
id: 4
},
success: function() {
$('#first').fadeOut({
duration: 400,
complete: function() {
console.log(wholePage.models)
compiled = _.template($('#page-temp').html(), {
page: wholePage
});
that.$el.html(compiled).delay(300).fadeIn();
}
});
}
});
}
});
var router = new Router();
var page_model = new Page();
var page_col = new Pages();
var home = new HomeView();
var about = new AboutView();
var contact = new ContactView();
var wholesale = new WholesaleView();
var products = new ProductView();
router.on('route:home', function() {
home.render();
});
router.on('route:about', function() {
about.render();
});
router.on('route:contact', function() {
contact.render();
});
router.on('route:wholesale', function() {
wholesale.render();
});
router.on('route:products', function() {
products.render();
});
Backbone.history.start();
</script>
Your anchor tag for shops has a trailing /
<a href="/#/products/">
Should be
<a href="/#/products">
Removing that made the route work for me.

Partial View not working propely in index view.

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
Now as we can see comment box, I called at run-time, which is partial view, but problem is I can add comment for only on first record...after first record that button wont work at all...
anything is missing ?
Is there separate process when we call any partial view run-time and make in action on it ?
See the pic...
Here is the code....
#model PagedList.IPagedList<CRMEntities.Customer>
<link href="../../Content/Paging.css" rel="stylesheet" type="text/css" />
<link href="../../Content/EventEntity.css" rel="stylesheet" type="text/css" />
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>" type="text/javascript"></script>
<div id="ListBox">
<div id="ListHeader">
All customers(#Model.TotalItemCount)
</div>
#foreach (var item in Model)
{
<div id="ListContent">
<span class="ContentTitleField">#Html.ActionLink(item.Name, "Details", new { id = item.Id }, new { #style="color:#1A6690;" })</span>
#if (item.Owner != null)
{
<span class="ContentSecondaryField">#Html.ActionLink(item.Owner.FullName, "Details", "Employee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
}
<span class="ContentSecondaryField">#Html.DisplayFor(modelItem => item.Address)</span>
<span id="flagMenus">
#Html.Action("ShowFlag", "Flagging", new { entityId=item.Id, entityType="Customer"})
</span>
#if (item.Opportunities.Count > 0)
{
<span class="FlagOpportunity">#Html.ActionLink("opportunities(" + item.Opportunities.Count + ")", "Index", "Opportunity", new { custid = item.Id }, new { #style = "color:#fff;" })</span>
}
<div style="float:right;">
#Html.Action("SetRate", "Rating", new { entityId = item.Id, rating = item.Rating, entityname = "Customer" })
</div>
<div id="subscribeStatus" style="float:right;">
#Html.Action("ShowSubscribedStatus", "Subscribing", new { entityId = item.Id, entityType = "Customer" })
</div>
<div class="ListLinks">
<span class="ListEditLinks">
<span style="float:left;">#Html.ActionLink("edit", "Edit", new { id = item.Id })</span>
<span class="LinkSeparator"></span>
</span>
<span class="ListAddLinks">
<span style="float:left;">#Html.ActionLink("+opportunity", "Create", "Opportunity", new { custid = item.Id }, null)</span>
<span class="LinkSeparator"></span>
<span>#Ajax.ActionLink("+Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</span>
<div class="RemarkBox"></div>
</div>
<span class="CommentAdd">
</span>
<div class="CommentBlock">
</div>
<span>#Ajax.ActionLink("Add Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</div>
}
<div class="PagingBox">
#Html.Action("CreateLinks", "Pager", new { hasPreviousPage = Model.HasPreviousPage, hasNextPage = Model.HasNextPage, pageNumber = Model.PageNumber, pageCount = Model.PageCount })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.RemarkBox').hide();
$('a.addremark').click(function () {
var url="#Html.Raw(Url.Action("ShowCommentBox", "Comment", new { Id = "idValue", EntityType = "Customer" }))";
url=url.replace("idValue",event.target.id);
$('.RemarkBox').load(url);
$(this).closest('div').find('div.RemarkBox').slideToggle(300);
return false;
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) { $("#customerlist").html(data); }
});
return false;
});
});
</script>
To expand on what Alberto León is saying, the partial page load will not cause the document ready event to fire, so the re-rendered elements will not have the javascript event handlers registered after the first comment is added.
To resolve this, you could put the event registration code into a function, and call this both from the document ready event and the success handler of the AJAX call. Something like this:
function AssignEventHandlers() {
$('a.addremark').click(function () {
....
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) {
$("#customerlist").html(data);
AssignEventHandlers();
}
});
return false;
});
}
$(document).ready(function () {
$('.RemarkBox').hide();
AssignEventHandlers();
}
In success function you need to recall the javascript, or the jquery code that makes the button work. Is an error that taked me a lot of time. Anything uploaded by ajax or any renderpartiAl needs to recall javascript.
$('.RemarkBox').load(url, function() {
//RECALL JAVASCRIPT
});

Categories